简体   繁体   English

python mysql select只返回表的第一行,而不是全部

[英]python mysql select return only first row of table, not all

im dealing with strage problem and this is like this:我正在处理奇怪的问题,这是这样的:

this query should return all of my table:此查询应返回我的所有表:

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 loop should print all rows in cursor but it will only print the first one. for 循环应该打印游标中的所有行,但它只会打印第一行。 it seems cursor is filled with first row only.似乎游标只填充了第一行。

is there anything that i missed here?有什么我在这里错过的吗? thanks谢谢

You need to put the output of cursor.fetchall() into a variable.您需要将 cursor.fetchall() 的输出放入一个变量中。 Like喜欢

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

Try尝试

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

you need a dic and save the result here你需要一个 dic 并将结果保存在这里

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

and if you need print any colum如果您需要打印任何列

print dic['table'][row]['colum']

This is not the correct way to use the .fetchall() method.这不是使用.fetchall()方法的正确方法。 Use cursor.stored_results() and then do a fetchall() on the results to perform this task, like this:使用cursor.stored_results()然后对结果执行fetchall()以执行此任务,如下所示:

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()

您可以尝试限制

cursor.execute("select * from mytable limit 1")

I also had this problem.我也有这个问题。 My mistake was that after inserting new row in the table I didn't commit the result.我的错误是在表中插入新行后我没有提交结果。 So you should add db.commit() after INSERT command.所以你应该在 INSERT 命令之后添加 db.commit() 。

i know its been very long time since, but i didnt find this answer anywhere else and thought it might help.我知道它已经很长时间了,但我没有在其他任何地方找到这个答案,并认为它可能会有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM