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()
相关推荐
笔头子26 分钟前
【Caché】数据库基础操作
数据库
上火的金鱼妹28 分钟前
redis集群部署与连接
数据库·redis·缓存
程序员-Benothing42 分钟前
MySQL 二级索引有 MVCC 快照吗?
数据库·mysql
xiaoxiangsiyan1 小时前
网络智能化转型核心模块全解析
运维·服务器·网络·数据库·学习·架构·php
不才不才不不才1 小时前
Spring 源码系列(25): @EnableTransactionManagement 与 TransactionInterceptor
java·数据库·spring
l1t1 小时前
DeepSeek总结的DuckDB访谈:DuckDB的崛起、扩展与AWS收购
数据库·云计算·aws·duckdb
隔窗听雨眠1 小时前
CI/CD测试数据清理完全指南:从污染根因到三层清理覆盖的完整方案
java·数据库·ci/cd
无定义_1 小时前
Bellman-Ford——贝尔曼福特算法
数据库·算法
盟接之桥1 小时前
半导体供应链破局:EDI如何成为中国制造的数字通行证
大数据·运维·服务器·网络·数据库·人工智能·制造
其实防守也摸鱼2 小时前
ZLibrary 类项目合规避坑指南:从技术实现到法律风险的全景梳理
运维·服务器·数据库·安全·自动化·github·copilot