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()
相关推荐
神王宝宝 王者小学3 小时前
HBase: 看上去很美
大数据·数据库·hbase
io无心4 小时前
Shardingsphere5分库分表
数据库·mysql
wWYy.5 小时前
Mysql:主键索引 唯一索引 普通索引 前缀索引
数据库·mysql
宝杰X75 小时前
Android Room3 多平台数据库
android·数据库
许彰午5 小时前
在PowerBuilder里手写Excel导出——OLE控制Excel的完整方案
excel
sky_8106138 小时前
Oracle ERP 各模块业务管理功能及底层表说明
数据库·oracle
YMatrix 官方技术社区10 小时前
CittaBase vs. Neo4j :原生图性能实测与混合检索实践
数据库·功能测试·ymatrix
闲猫11 小时前
LangChain / Integrations / Integrations by component / Tool
java·数据库·langchain
xqqxqxxq11 小时前
SQL 连接查询技术笔记
数据库·笔记·sql
在世修行11 小时前
Windows 上 Docker Desktop 部署 MySQL + TDengine 全过程(含 WSL 报错与镜像加速排障实战)
windows·mysql·docker·tdengine