import pandas as pd
import csv
import pymysql
def JoinDB():
conn = pymysql.connect(host='localhost', user='root', passwd='passwd', db='DB')
##创建游标
cur = conn.cursor()
##执行sql语句
count=cur.execute('select * from user')
print('总共有%s条数据' %count)
# 搜取所有结果
results = cur.fetchall()
# 获取表的数据结构字段
fields = cur.description
return list(results), list(fields)
S=JoinDB()
# print(S[0][i])
# print(S[1][i][0])
results=S[0]
fields=S[1]
print(results)
print(fields)
# print(fields[0][0])
# print(results)
# #写入文件
def writer_file(results,fields):
##查看文件大小
file_size = os.path.getsize('/home/kiosk/Flask_Movie_Site-master/app/数据库转文件存储/data.csv')
if file_size == 0:
##表头
name=[]
results_list=[]
for i in range(len(fields)):
name.append(fields[i][0])
print(name)
for i in range(len(results)):
results_list.append(results[i])
##建立DataFrame对象
file_test = pd.DataFrame(columns=name, data=results_list)
##数据写入,不要索引
file_test.to_csv('/home/kiosk/Flask_Movie_Site-master/app/数据库转文件存储/data.csv', encoding='utf-8', index=False)
else:
with open('/home/kiosk/Flask_Movie_Site-master/app/数据库转文件存储/data.csv', 'a+', newline='') as file_test:
##追加到文件后面
writer = csv.writer(file_test)
##写文件
writer.writerows(results)
if __name__ == '__main__':
writer_file(results,fields)
版权声明:本文为qq_41661056原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。