mysql数据库中多张表导出成excel方式

需求:

用于将mysql数据库中的几百张表导出成excel方式

表中有些字段的值是含有双引号和逗号值,比如json值

表中有些字段是汉字内容

导出的excel要求有表的列名

shell对于含有逗号和双引号的值会错乱分割

数据库中某些字段值是化学符号

python 复制代码
import pymysql,os,csv,shutil
target_dir=r'C:\Users\XXX\Desktop\excel'
if  os.path.exists(target_dir):
	shutil.rmtree(target_dir)
	os.mkdir(target_dir)
else:
	os.mkdir(target_dir)

myconn=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='rhtx')
table_sql="select table_name from information_schema.tables where table_schema='rhtx'"
with myconn.cursor() as cursor:
	cursor.execute(table_sql)
	table_name=list(cursor.fetchall())

for name in table_name:
	file_name=name[0]+".csv"
	file_path = os.path.join(target_dir, file_name)
	sql='select * from '+'rhtx.'+name[0]
	with myconn.cursor() as cursor:
		cursor.execute(sql)
		rows=cursor.fetchall()
		with open(file_path, mode='w', newline='',encoding='gbk') as file:
			writer=csv.writer(file)
			writer.writerow([i[0] for i in cursor.description])
			writer.writerows(rows)
myconn.close()
相关推荐
徐同保5 小时前
python异步函数语法解析,async with ... as ...语法解析
数据库·python·oracle
是梦终空5 小时前
计算机毕业设计266—基于Springboot+Vue3的共享单车管理系统(源代码+数据库)
数据库·spring boot·vue·课程设计·计算机毕业设计·源代码·共享单车系统
a285285 小时前
nginx的重定向
大数据·数据库·nginx
蒂法就是我5 小时前
mysql主键索引和其他索引区别在哪里?
数据库·mysql
eWidget5 小时前
数据可视化进阶:Seaborn 柱状图、散点图与相关性分析
数据库·python·信息可视化·kingbase·数据库平替用金仓·金仓数据库
X54先生(人文科技)5 小时前
20260211_AdviceForTraditionalProgrammers
数据库·人工智能·ai编程
橘子137 小时前
redis持久化
数据库·redis
jghhh019 小时前
LT喷泉码编解码的MATLAB实现
数据库·算法·matlab
PD我是你的真爱粉10 小时前
MySQL8新特性
数据库·mysql