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()
相关推荐
2501_9454235429 分钟前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
gameboy0312 小时前
从MySQL迁移到PostgreSQL的完整指南
数据库·mysql·postgresql
xdl25992 小时前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis
回到原点的码农2 小时前
Spring Data JDBC 详解
java·数据库·spring
zb200641202 小时前
Spring Boot 实战:轻松实现文件上传与下载功能
java·数据库·spring boot
CSharp精选营3 小时前
SQL Server安装避坑:这8个奇葩报错你遇到过几个?
数据库·sql server·安装指南·避坑
一勺菠萝丶3 小时前
Flowable + Spring 集成踩坑:流程结束监听器查询历史任务为空 & 获取不到审批意见
java·数据库·spring
RDCJM3 小时前
mysql表添加索引
数据库·mysql
czlczl200209254 小时前
Redis命令处理逻辑模型
数据库·redis·缓存
楼兰胡杨4 小时前
面试题|MySQL 的 3 层主键索引最多能支撑多少数据量
mysql·面试题