0

I'm using python 3.5.2 for my project. I installed MySQLdb via pip for Mysql connection.

Code:

import MySQLdb

class DB:
    def __init__(self):
        self.con = MySQLdb.connect(host="127.0.0.1", user="*", passwd="*", db="*")
        self.cur = self.con.cursor()

    def query(self, q):
        r = self.cur.execute(q)
        return r

def test():
    db = DB()
    result = db.query('SELECT id, name FROM test')
    return print(result)

def test1():
    db = DB()
    result = db.query('SELECT id, name FROM test').fetchall()
    for res in result:
        id, name = res
        print(id, name)

test()
test1()
#test output >>> '3'
#test1 output >>> AttributeError: 'int' object has no attribute 'fetchall'

Test table:

id     |     name
1      |    'test'
2      |    'test2'
3      |    'test3'

2 Answers 2

1

Please read this link:http://mysql-python.sourceforge.net/MySQLdb.html

At this point your query has been executed and you need to get the results. You have two options:

r=db.store_result()

...or... r=db.use_result() Both methods return a result object. What's the difference? store_result() returns the entire result set to

the client immediately. If your result set is really large, this could be a problem. One way around this is to add a LIMIT clause to your query, to limit the number of rows returned. The other is to use use_result(), which keeps the result set in the server and sends it row-by-row when you fetch. This does, however, tie up server resources, and it ties up the connection: You cannot do any more queries until you have fetched all the rows. Generally I recommend using store_result() unless your result set is really huge and you can't use LIMIT for some reason.

def test1():
    db = DB()
    db.query('SELECT id, name FROM test')
    result = db.cur.fetchall()
    for res in result:
        id, name = res
        print(id, name)
Sign up to request clarification or add additional context in comments.

Comments

0

cursor.execute() will return the number of rows modified or retrieved, just like in PHP. Have you tried to return the fetchall() like so?

 def query(self, q):
   r = self.cur.execute(q).fetchall()
   return r

See here for more documentation: https://ianhowson.com/blog/a-quick-guide-to-using-mysql-in-python/

1 Comment

this is wrong, it will return error like '' int can't be iterated'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.