1

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

7 Answers 7

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

You can try limit:

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

Comments

0

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

1 Comment

it returns an error "for row in cursor.execute("select * from mytable"): TypeError: 'long' object is not iterable"
0

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']

Comments

0

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.