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()
相关推荐
小羊没烦恼!2 小时前
T-SQL查询高级—SQL Server索引中的碎片和填充因子
开发语言·前端·javascript·数据库·后端·python·web安全
lv__pf3 小时前
redis【TL redis(6)】
数据库·redis·缓存
冰暮流星3 小时前
mysql索引失效的情形
数据库·笔记·sql·mysql
IvorySQL3 小时前
IvorySQL 校园行走进山东大学:从 PostgreSQL 到 AI,连接技术实践与职业成长
数据库·人工智能·postgresql
广州智造3 小时前
Radioss 材料本构的二次开发
运维·数据库·自动化·建模·后处理·前处理
闲云自留地3 小时前
从零造一台 Ubuntu 24.04:虚拟机、装系统、配 IP 到 root 远程登录一篇通
数据库·tcp/ip·ubuntu
Allen-Steven3 小时前
SQL查询专项:从完整书写到综合判断
运维·服务器·数据库
Navicat中国3 小时前
SQL 编辑器生产力:重构与实时错误检测
数据库·sql·重构·编辑器·navicat
Data analyse4563 小时前
App埋点版本兼容的字段迁移校验
大数据·运维·服务器·前端·数据库·数据分析
Data analyse4563 小时前
Nginx日志访客识别的边界处理
大数据·运维·服务器·数据库·数据分析