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()
相关推荐
APIshop22 分钟前
Python 爬虫获取京东商品详情 API 接口实战指南
java·服务器·数据库
XmasWu122526 分钟前
【Hermes Agent进阶】开发自定义技能
网络·数据库
刘~浪地球28 分钟前
数据库性能优化实战
数据库·性能优化
2401_8654396330 分钟前
CSS怎么在flex布局中实现项目均分间距_设置justify-content space-evenly
jvm·数据库·python
m0_4939345330 分钟前
CSS如何实现输入框禁用样式_使用-disabled伪类设定
jvm·数据库·python
yanweijie031736 分钟前
对比VLOOKUP、XLOOKUP、INDEX+MATCH三大查找函数
excel
m0_7164300738 分钟前
如何用 classList.toggle 实现侧边栏菜单的点击展开与收起
jvm·数据库·python
爪洼传承人40 分钟前
AI工具MCP的配置,慢sql优化
android·数据库·sql
Aloudata1 小时前
PL/SQL 存储过程血缘解析指南:攻克数据治理的「最后堡垒」
数据库·sql·数据治理·数据管理·元数据·数据血缘
Francek Chen1 小时前
【大数据存储与管理】NoSQL数据库:03 NoSQL与关系数据库的比较
大数据·数据库·分布式·nosql