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()
相关推荐
Escalating_xu5 小时前
【MySQL】事务管理(上):从 ACID 到提交回滚,把一次转账真正做完整
android·数据库·mysql
不喝水就会渴7 小时前
「不想上班」实战系列:密码卡证保险箱 —— 主密钥存入 Asset,密文落库 RDB【鸿蒙心迹】
数据库·oracle
西泽XIZ97 小时前
微信小程序网络与数据库交互实践:从后端环境搭建到数据渲染
网络·数据库·微信小程序·小程序
TiDB 社区干货传送门9 小时前
平凯数据库携手东软医保共筑智慧医保,构建可靠、安全、开放的数据底座
数据库·tidb·国产数据库
YYYing.11 小时前
【Mysql剑指offer系列 (七) 】MySQL性能调优和架构
数据库·mysql·八股
Decay__12 小时前
PostgreSQL WAL 归档与时间点恢复 —— WAL 连续归档、recovery_target 时点恢复与 pg_rewind
运维·数据库·sql·postgresql
如夏倾城13 小时前
大模型(Large Model)解析:从数据类型、模型架构到任务选型
服务器·网络·数据库·语言模型·架构·audiolm
船神丿男人13 小时前
Redis 缓存击穿与雪崩实测:同键合并、TTL 错峰与迟到回填
数据库·redis·缓存
yuzhiboyouye14 小时前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql