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()
相关推荐
java_logo4 分钟前
Docker 部署 Hue:轻松搭建数据库与数据仓库 SQL 查询平台
数据库·数据仓库·sql·docker·hue·部署教程·轩辕镜像
Davina_yu8 分钟前
1、count(*)、count(1) 和 count(单个字段) 的区别
数据库
锦衣夜行?8 分钟前
Oracle 数据库安装失败清理残留步骤
数据库·oracle
时间售卖铺22 分钟前
MySQL 表的约束
运维·数据库·mysql·云原生
一条泥憨鱼27 分钟前
【Redis | 黑马点评】基于Redis的消息队列 | stream消息队列 源码解读
java·数据库·redis·缓存·lua
CodeGL27 分钟前
9、Python基础之IO编程
开发语言·数据库·python
每天一道题29 分钟前
Redis 缓存为什么会出问题?穿透、击穿、雪崩与缓存一致性
数据库·redis·缓存
tongyiixiaohuang1 小时前
物料成本核算单同步返回信息策略实战教程:从金蝶云星空回写 MySQL 的闭环设计
数据库·mysql
星云低代码开发平台1 小时前
AI 工作台记录删除与业务审计留存:三层数据边界设计
数据库·人工智能·架构
深度学习04071 小时前
MySQL InnoDB Cluster 部署完整文档
android·mysql·adb