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()
相关推荐
qianshang23315 分钟前
SQL注入学习总结
网络·数据库·渗透
what丶k41 分钟前
深入解析Redis数据持久化:RBD机制原理、实操与生产最佳实践
数据库·redis·缓存
瀚高PG实验室1 小时前
通过数据库日志获取数据库中的慢SQL
数据库·sql·瀚高数据库
Hgfdsaqwr2 小时前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
invicinble2 小时前
对于Mysql深入理解
数据库·mysql
阳光九叶草LXGZXJ2 小时前
达梦数据库-学习-47-DmDrs控制台命令(LSN、启停、装载)
linux·运维·数据库·sql·学习
Hgfdsaqwr2 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
s1hiyu3 小时前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
2301_763472463 小时前
使用Seaborn绘制统计图形:更美更简单
jvm·数据库·python
熊文豪3 小时前
金仓数据库如何以“多模融合“重塑文档数据库新范式
数据库·金仓数据库·电科金仓·mongodb迁移