0

我正在处理战略问题,就像这样:

此查询应返回我的所有表:

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
cursor.fetchall()
for row in cursor:
print row

for 循环应该打印光标中的所有行,但它只会打印第一行。似乎光标只填充了第一行。

有什么我想念的吗?谢谢

4

7 回答 7

3

您需要将 cursor.fetchall() 的输出放入一个变量中。喜欢

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
rows = cursor.fetchall()
for row in rows:
    print row
于 2013-06-26T16:46:00.367 回答
0

这不是使用该方法的正确.fetchall()方法。使用cursor.stored_results()然后fetchall()对结果执行 a 来执行此任务,如下所示:

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
results = cursor.stored_results()
for result in results:
    print result.fetchall()
于 2014-12-10T23:44:01.213 回答
0

你需要一个 dic 并将结果保存在这里

dic={}
cursor.execute("select * from table")
dic['table']=cursor.fetchall()
for row in range(len(dic['table'])):
    print dic['table'][row]

如果您需要打印任何列

print dic['table'][row]['colum']
于 2013-06-26T19:11:52.333 回答
0

尝试

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
for row in cursor.execute("select * from mytable"):
    print row
于 2013-06-26T17:19:11.663 回答
0

您可以尝试限制

cursor.execute("select * from mytable limit 1")
于 2016-10-07T02:28:40.667 回答
0

我也有这个问题。我的错误是在表中插入新行后我没有提交结果。所以你应该在 INSERT 命令之后添加 db.commit() 。

于 2017-03-26T17:24:12.447 回答
0

我知道它已经很久了,但我没有在其他任何地方找到这个答案,并认为它可能会有所帮助。

cursor.execute("SELECT top 1 * FROM my_table")

于 2021-01-18T12:03:48.087 回答