简体   繁体   English

如何使用 fetchmany 将 mysql 表转储到 csv 中

[英]How to dump mysql table into csv using fetchmany

I have a big mysql table and I want to export it to csv file using python.我有一个很大的 mysql 表,我想使用 python 将它导出到 csv 文件。 However, when I use cursor.fetchall() my laptop hangs and when I use但是,当我使用 cursor.fetchall() 时,我的笔记本电脑挂了,当我使用

cursor.execute("select * from table_name")
while True:
     rows = cursor.fetchmany(1000);
     while rows is not None:
         with open(table_name + ".csv", "a+") as csvfile:
             writer = csv.writer(csvfile, delimiter=',')
             writer.writerow(rows)
csvfile.close()

the loop wont stop and in the csv file the same rows are written multiple times.循环不会停止,并且在 csv 文件中多次写入相同的行。 How to move mysql table to csv little by little?如何一点一点地将mysql表移动到csv? Thank you for the help.感谢您的帮助。

you are using while loop which never ends as there is no any break condition.您正在使用永远不会结束的 while 循环,因为没有任何中断条件。

Please use while loops very carefully.请非常小心地使用 while 循环。

You can try below code(assuming rows is the list of records):您可以尝试以下代码(假设行是记录列表):

cursor.execute("select * from table_name")
rows = cursor.fetchall()
with open(table_name + ".csv", "a+") as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for row in rows:
        writer.writerow(row)

You can execute this query to output whatever table to a .CSV file on your desired location on your drive.您可以执行此查询以将任何表输出到驱动器上所需位置的 .CSV 文件。

SELECT *
FROM tablename
INTO OUTFILE 'C:\data.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

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

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