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()
相关推荐
墨神谕8 分钟前
什么是回表查询
mysql
Elastic 中国社区官方博客11 分钟前
将 Logstash 管道从 Azure Event Hubs 迁移到 Kafka 输入插件
大数据·数据库·elasticsearch·microsoft·搜索引擎·kafka·azure
草莓熊Lotso11 分钟前
MySQL 事务管理全解:从 ACID 特性、隔离级别到 MVCC 底层原理
linux·运维·服务器·c语言·数据库·c++·mysql
鸽芷咕16 分钟前
Oracle 替代工程实践深度解析:金仓全链路工程实践 —— 从评估决策到平滑上线的深度技术攻坚
数据库·oracle
gushinghsjj30 分钟前
元数据管理包含哪些?元数据管理如何支持数据分析?
数据库·oracle·数据分析
不愿透露姓名的大鹏36 分钟前
MySQL InnoDB核心参数深度优化/性能调优
运维·服务器·数据库·mysql
heimeiyingwang39 分钟前
【架构实战】图数据库Neo4j在社交系统中的应用
数据库·架构·neo4j
夕除44 分钟前
MVN--06
数据库·sql·mybatis
鸠摩智首席音效师44 分钟前
如何在 MacOS 上安装 PostgreSQL ?
数据库·macos·postgresql