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()
相关推荐
2601_962056236 小时前
EasyMarkets易信:比特币基金流入创年内新高
人工智能·mysql
2601_962056236 小时前
EasyMarkets:“网络安全需求持续升温”
数据库·人工智能
润乾软件6 小时前
SQLazy:合并有重叠的时间区间
数据库·sql·sqlazy
拾光Ծ6 小时前
【MySQL】复合查询、表的连接
java·数据库·sql·mysql
吃饱了得干活6 小时前
MySQL 进阶:锁与事务、执行计划、内存管理、高可用架构及 8.0 新特性
后端·mysql
SunnyDays10116 小时前
如何使用 Python 添加和编辑 Excel VBA 宏(无需安装 Excel)
开发语言·python·excel·vba
Knight_AL7 小时前
MySQL 递归 CTE:WITH RECURSIVE 用法详解
android·数据库·mysql
数据狐(Datafox)7 小时前
mercadolibre.item_get 工程实战:美客多商品详情API技术解析与落地应用
java·人工智能·mysql·json
GHL2842710907 小时前
codex操作excel学习
学习·ai·word·excel