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()
相关推荐
Arva .2 小时前
深分页与游标
数据库·oracle
idolao2 小时前
MySQL 5.7 安装教程:详细步骤+自定义安装+命令行客户端配置(Windows版)
数据库·windows·mysql
20年编程老鸟java+ai全栈3 小时前
mysql、pg、oracel数据库迁移避坑指南
数据库·mysql
Rsun045513 小时前
Redis中实现访问量计数
数据库·redis·缓存
西柚0013 小时前
Ubuntu22.04.5 + Docker + MySQL 5.7
mysql·docker·容器
天空属于哈夫克34 小时前
自动化素材中枢:实现云端文件与外部群消息的异步同步方案
数据库·oracle
Navicat中国4 小时前
Navicat Premium Lite 正式登录鸿蒙应用市场
数据库·华为·harmonyos·navicat
Yvonne爱编码4 小时前
数据库---Day 1 数据库基础
数据库·mysql·oracle
Ricky_Theseus4 小时前
数据库关系代数 - 连接操作
linux·数据库·算法
FL4m3Y4n4 小时前
MySQL索引原理与SQL优化
android·sql·mysql