自从大学时代以来,我对sql和python非常生疏。
我想知道如何逐行读取查询结果而不是fetchall?
这是我目前的测试代码:
#!/usr/bin/python
import time
import csv
import mysql.connector
start_time = time.time()
cnx = mysql.connector.connect(user='user', password='1234',
host='10.0.10.100',
database='serverDB')
try:
cursor = cnx.cursor()
cursor.execute("select * from serverDB.task")
result = cursor.fetchall()
with open("query.csv", "wb") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow([i[0] for i in cursor.description]) # write headers
csv_writer.writerows(result)
for x, row in enumerate(result):
print x
print row
#print result
finally:
cnx.close()
print "there are ", numrows, "rows"
print("--- %s seconds ---" % (time.time() - start_time))
答案 0 :(得分:1)
有一个名为fetchone
的函数。该功能的用法如下:
connect = MySQLdb.connect(......)
cursor = connect.cursor()
cursor.execute('select......')
row_count = cursor.rowcount
for i in range(row_count):
line = cursor.fetchone() #you can operate each line