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()
相关推荐
落叶-IT22 分钟前
Java异常处理深度实战教程:异常传播的失败场景分析
数据库·oracle
执子手 吹散苍茫茫烟波1 小时前
常见的数据库隔离级别以及企业里常用的是什么方案
数据库
Database_Cool_2 小时前
数据库慢查询优化首选方案:阿里云 RDS 性能洞察+自动诊断
数据库·人工智能·阿里云
YOU OU2 小时前
Redis初识
数据库·redis·缓存
长孙豪翔2 小时前
在.net中读写config文件的各种方法
java·数据库·.net
深盾科技_Virbox3 小时前
加密狗授权能力选型:从授权模型到全生命周期管理
java·网络·数据库
峥无3 小时前
深入理解MySQL事务与MVCC机制
数据库·mysql
行思理4 小时前
MongoDB 大数据备份,新手教程
数据库·mongodb
-To be number.wan4 小时前
数据库系统 | 规范化理论
数据库·学习
城数派5 小时前
1950-2026年中国0.1°逐月平均气温栅格数据集
数据库·信息可视化