Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python AttributeError:“long”对象没有属性“fetchall”_Python_Mysql_Flask - Fatal编程技术网

Python AttributeError:“long”对象没有属性“fetchall”

Python AttributeError:“long”对象没有属性“fetchall”,python,mysql,flask,Python,Mysql,Flask,我正在尝试使用mysql flask python扩展执行一些sql。由于某些原因,下面的代码总是返回long stringify = lambda x : '"' + x + '"' if request.method == 'POST': sql = "select * from users where username = " + stringify(request.form['username']) user = g.db.cursor().execute

我正在尝试使用mysql flask python扩展执行一些sql。由于某些原因,下面的代码总是返回long

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()
错误:

 user = g.db.cursor().execute(sql).fetchall()
AttributeError: 'long' object has no attribute 'fetchall'
为什么不返回结果集

而且,我可以很好地执行insert语句

修正答案:

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

您试图对Cursor.execute的结果调用一个方法,该方法表示未定义。您正在使用的实现似乎返回一个整数。相反,您希望在游标对象上调用fetchall。比如:

cursor = g.db.cursor()
cursor.execute(sql)
user = cursor.fetchall()

您可能还需要研究字符串格式,尤其是使用execute函数。您可以编写sql='select*FROM username=%s'的用户,然后编写cursor.executesql,request.form.username,请参见这里的示例如何将其转换为字典?返回的对象似乎非常原始。如果没有关于返回哪些列的更多信息,即调用dict,则无法确定如何设置键。您可以使用光标上的description属性来确定列是什么。这就是说,如果您请求所需的数据,而不是请求所有列,那么您的代码将更加健壮,这样您就应该知道每个元组项是什么。如果你需要一个更高级的接口,也许考虑使用一个类似于ORM的Storm,SqLalCyy或Django的ORM。我肯定会和SqlAlchemy一起使用,但是这个项目的要求不允许ORMsGot:DEF GETY-DATAG,SQL:光标= G.Db.Curror CursRo.ExtruTeSql数据= [ DistCurror .Debug [IDX](0)]。,idx的值,enumeraterow中的值对应游标中的行。fetchall]返回数据