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()
相关推荐
小马过河R9 小时前
真实场景:用户自建定时任务与推送提醒Agent-架构设计与可靠性实践
数据库·人工智能·agent·vibe coding·ai coding
鹤落晴春10 小时前
【MySQL】 | 两阶段提交、主从复制
运维·数据库·mysql
SelectDB11 小时前
中小企业数据仓库怎么选?按数据规模、BI 并发和国产化要求分三档
数据库
SelectDB11 小时前
数据仓库一年要花多少钱?云数仓、自建 Doris 成本拆解与 TCO 计算指南
数据库
码少女12 小时前
MySQL——复杂查询
数据库·mysql
codeejun13 小时前
每日一Go·MySQL-20、SQL 性能调优实战总结
sql·mysql·golang
CoderYanger14 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
TDengine (老段)14 小时前
TDengine 读缓存与 LAST 查询完全指南
大数据·数据库·物联网·缓存·时序数据库·tdengine·涛思数据
FungLeo16 小时前
FengCMS · PHP+MySQL 升级实录 · 输出转义的度:面包屑双重编码、默认转义与 cms_html()信任声明
mysql·html·php·fengcms·输出转义
Decay__17 小时前
PostgreSQL 用户权限与安全 —— 角色体系、GRANT 授权、pg_hba.conf 认证、行级安全与审计
运维·数据库·sql·postgresql