简体   繁体   中英

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. 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. 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={}
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. Use cursor.stored_results() and then do a fetchall() on the results to perform this task, like this:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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