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()
相关推荐
初圣魔门首席弟子4 分钟前
Qt C++ 项目实战:修改共享头文件后的高效增量编译与快速发布流程
数据库
wb043072015 分钟前
仓库搬家不停业——从阿明的“在线换仓库“,看数据库迁移与 Schema 演进的实战方法论
数据库·adb·架构
lx188548698969 分钟前
Redis大Key阻塞:单线程CPU100%的致命陷阱
数据库·redis·缓存
IT策士12 分钟前
Redis 从入门到精通:位图、HyperLogLog、GEO
数据库·redis·缓存
拄杖忙学轻声码22 分钟前
mysql脚本查询数据,符合指定条件的排在数据列表最前面,实现方式
mysql
IT策士26 分钟前
Redis 从入门到精通:Python 操作 Redis 进阶
数据库·redis·python
IvorySQL32 分钟前
PostgreSQL 技术日报 (6月8日)|索引预取迭代,AI 安全功能上新
数据库·人工智能·sql·安全·postgresql
阿正的梦工坊40 分钟前
【Rust】05-结构体、枚举与模式匹配
java·数据库·rust
cjp56042 分钟前
006.WEB_API使用本地数据库 SQLite + Dapper 入门教程
数据库·sqlite
新新学长搞科研44 分钟前
【广东省博促会主办】2026年第七届先进材料与智能制造国际学术会议(ICAMIM 2026)
大数据·前端·数据库·人工智能·物联网