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()
相关推荐
九皇叔叔1 小时前
【9】PostgreSQL 之 vacuum 死元组清理
数据库·postgresql
风雅的远行者1 小时前
mysql互为主从失效,重新同步
数据库·mysql
晨岳1 小时前
CentOS 安装 JDK+ NGINX+ Tomcat + Redis + MySQL搭建项目环境
java·redis·mysql·nginx·centos·tomcat
宇钶宇夕2 小时前
S7-1200 系列 PLC 中 SCL 语言的 PEEK 和 POKE 指令使用详解
运维·服务器·数据库·程序人生·自动化
绿蚁新亭2 小时前
Spring的事务控制——学习历程
数据库·学习·spring
scilwb3 小时前
占用栅格地图数据集
数据库
时序数据说4 小时前
时序数据库的存储之道:从数据特性看技术要点
大数据·数据库·物联网·开源·时序数据库·iotdb
鸥梨菌Honevid5 小时前
QT解析文本框数据——概述
数据库·qt·mysql
今天又得骑车了5 小时前
一、MySQL 8.0 之《EXPLAIN ANALYZE 执行计划》
数据库·mysql·database
icecreamstorm5 小时前
MySQL 事务 最全入门
后端·mysql