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()
相关推荐
星马梦缘3 小时前
数据库作战记录1
数据库·sql·mysql
短剑重铸之日5 小时前
《ShardingSphere解读》07 读写分离:如何集成分库分表+数据库主从架构?
java·数据库·后端·架构·shardingsphere·分库分表
njidf5 小时前
用Python制作一个文字冒险游戏
jvm·数据库·python
鸡蛋灌Bean5 小时前
MySQL优化系列
数据库·mysql
数巨小码人6 小时前
平滑迁移:传统到国产数据库的2026转型之路
数据库
麦聪聊数据6 小时前
QuickAPI 在系统数据 API 化中的架构选型与集成
数据库·sql·低代码·微服务·架构
2403_835568476 小时前
自然语言处理(NLP)入门:使用NLTK和Spacy
jvm·数据库·python
wal13145206 小时前
Dify发布V1.13.1版本,Hologres 向量数据库支持、HITL 邮件 Markdown 渲染及多项安全加固
数据库·安全·dify
Leon-Ning Liu7 小时前
Oracle UNDO表空间文件误删除故障恢复
数据库·oracle
2301_776508727 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python