我试图将一个Mysql表写入一个csv文件,当我这样做时,表中的某些行丢失了(它们在哪里消失了?)。当我将Mysql表写入txt文件时,没有丢失任何行。这是代码:
import pymysql
import csv
db1 = pymysql.connect(host="localhost",
user="root",
password='secret',
port=3306,
db='world'
)
try :
with db1.cursor() as cursor:
# Read all 4079 lines
sql = 'select * from city;'
cursor.execute(sql)
result = cursor.fetchall()
#csv file contains 4063 lines instead of 4079
c = csv.writer(open("db_csv.csv", "w", newline='\n', encoding='UTF-8'))
c.writerows(result)
#txt file contains 4079 lines
with open('db_txt.txt', 'w') as file:
for row in result:
file.write(str(row))
finally:
db1.close()