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()
相关推荐
Nturmoils13 小时前
只面对一张表:KingbaseES 超表如何简化海量时序数据管理
数据库
starrocks_stella14 小时前
StarRocks 如何查询 Paimon 半结构化数据?Variant、Shredding 与 SQL 实践
数据库
这个DBA有点耶14 小时前
MySQL迁移实战:从mysqldump到专业工具的完整选型指南
数据库·mysql·dba
小白说大模型14 小时前
LLM集成数据库的幻觉治理:当AI给出的SQL建议是错的
数据库·人工智能·sql·oracle·重构·开源
zcmodeltech15 小时前
工程机械与矿山机械沙盘模型多系统协同控制系统设计:基于STM32与Modbus RTU的露天开采-井下掘进-智慧矿山全场景联动方案
数据库·stm32·单片机·嵌入式硬件·制造·多分类
曹牧15 小时前
Oracle:空值排序
数据库·oracle
SelectDB15 小时前
Apache Doris 与 StarRocks 深度对比:2026 年 OLAP 引擎选型指南
数据库
lbb 小魔仙15 小时前
谁替 AI Agent 记住时间?——从航海钟到智能数据库,三百年时延坍缩史
数据库·人工智能·db
这个DBA有点耶16 小时前
读懂半连接:IN/EXISTS子查询什么时候快、什么时候慢?
数据库·性能优化·架构