Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'long' object has no attribute 'fetchall'

I'm attempting to execute some sql using the mysql-flask python extension. The below code always returns a long for some reason.

stringify = lambda x : '"' + x + '"'
if request.method == 'POST':
        sql = "select * from users where username = " + stringify(request.form['username'])
        user = g.db.cursor().execute(sql).fetchall()

Error:

 user = g.db.cursor().execute(sql).fetchall()
AttributeError: 'long' object has no attribute 'fetchall'

Why doesn't this return a result set?

Also, I can execute insert statements just fine.

FIX (ANSWER):

def get_data(g, sql):
    cursor = g.db.cursor()
    cursor.execute(sql)
    data = [dict((cursor.description[idx][0], value) for idx, value in enumerate(row)) for row in cursor.fetchall()]
    return data
like image 882
The Internet Avatar asked Nov 16 '12 05:11

The Internet


1 Answers

You are trying to call a method on the result of Cursor.execute, which the DB-API specification says is undefined (the implementation you're using appears to be returning an integer). Instead, you want to call fetchall on the cursor object. Something like:

cursor = g.db.cursor()
cursor.execute(sql)
user = cursor.fetchall()
like image 155
James Henstridge Avatar answered Nov 14 '22 00:11

James Henstridge