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()
相关推荐
小鱼冻干15 分钟前
express中间件
前端·mysql·node.js
Liii40325 分钟前
Java学习——数据库查询操作
java·数据库·学习
Databend2 小时前
从 Snowflake 到 Databend Cloud:全球游戏平台借助 Databend 实现实时数据处理
数据库
凭君语未可2 小时前
MySQL中的事务隔离级别有哪些
数据库·mysql
笑远2 小时前
Oracle Data Guard(数据保护)详解
数据库·oracle
拾柒SHY2 小时前
iwebsec-SQL数字型注入
数据库·sql·web安全·网络安全
Pandaconda2 小时前
【后端开发面试题】每日 3 题(十五)
数据库·分布式·后端·python·面试·后端开发·幂等性
杜子腾dd3 小时前
17.使用读写包操作Excel文件:pyxlsb 包
python·数据挖掘·excel·numpy·pandas
运维小贺4 小时前
MySQL超详细介绍(近2万字)
运维·数据库·mysql
猫咪-95274 小时前
Mysql表的简单操作
服务器·数据库·mysql