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()
相关推荐
asdzx675 分钟前
Excel 水印方案对比:页眉图片 vs 背景图片(附 C# 实现)
c#·excel
fb_123459 分钟前
MySQL基础核心|数据库原理+MySQL详解
数据库·mysql
‎ദ്ദിᵔ.˛.ᵔ₎15 分钟前
Mysql 基本查询
数据库·mysql
-madongyu-22 分钟前
GaussDB 性能调优:等待事件、慢 SQL 定位与关键参数
数据库·sql·gaussdb
-madongyu-33 分钟前
GaussDB 部署规划:磁盘水位、RAID 与端口设计
数据库·gaussdb
weixin_511255217 小时前
MySQL升级记录
数据库·mysql
程序猿乐锅8 小时前
【黑马点评 | 第八篇】Redisson分布式锁
java·数据库·spring boot·redis·分布式·spring·缓存
Leo.yuan9 小时前
2026年本地化Data Agent优质厂商盘点:哪些产品更适合企业生产环境
大数据·数据库·人工智能
做运维的阿瑞9 小时前
数据库增删改的安全写法
数据库·sql·mysql
程序边界9 小时前
迁移评估不再拍脑袋,这个数据迁移工具的量化报告把我救了(上)
数据库