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()
相关推荐
csdn_aspnet1 小时前
Docker MySql 5.7、MySql8.x 进阶配置
mysql·docker·容器
城北徐宫9 小时前
MySQL数据类型整理
数据库·mysql
数据库小学妹9 小时前
数据库容量规划:四个数与扩容触发线
运维·数据库·后端
时间的拾荒人9 小时前
Redis Cluster 集群详解:分片算法、搭建、故障处理与扩容实战
数据库·redis·算法·集群
纆兰12 小时前
MySQL的多表查询
数据库·mysql
七夜zippoe12 小时前
Nexent 模型配置:4 字段与 9 个槽位
数据库·人工智能·模型·nexent
进击的荆棘13 小时前
MySQL——表的操作
数据库·mysql
小番茄程序猿13 小时前
一条 ALTER 拖死全表:MDL 阻塞的完整时间线(8.4.11 实测)
后端·mysql
nice_lcj52014 小时前
MySQL 慢查询与 EXPLAIN:怎么定位、怎么优化
java·数据库·后端·mysql
OceanRoy1 天前
数据库表的设计
数据库·内连接·外连接·er图·表的约束·三大范式·多表连接