8

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
4

1 回答 1

13

您正在尝试对 的结果调用方法Cursor.executeDB-API 规范称该方法未定义(您正在使用的实现似乎返回一个整数)。相反,您想调用fetchall游标对象。就像是:

cursor = g.db.cursor()
cursor.execute(sql)
user = cursor.fetchall()
于 2012-11-16T06:06:28.607 回答