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()
相关推荐
用户8003913878326 分钟前
使用 Gemini 解决 MySQL 常见问题
mysql
赵渝强老师35 分钟前
【赵渝强老师】openGauss的数据库
数据库·opengauss·国产数据库·高斯数据库
HackTwoHub42 分钟前
Sqli-Scanner SQL注入SKILL自动化挖掘SQL注入,零依赖自动化SQL注入挖掘,赏金猎人
数据库·人工智能·sql·web安全·网络安全·自动化·系统安全
l1t1 小时前
DuckDB对group by cube / rollup / groupping sets查询的优化
数据库·duckdb
Database_Cool_1 小时前
什么是湖仓一体?和数据仓库的本质区别(附 AnalyticDB MySQL 湖仓一体方案)
数据库·数据仓库·mysql
Channing Lewis2 小时前
PHP 解析 Excel 的那些坑:一次“行号错位”引发的数据丢失
开发语言·php·excel
l1t2 小时前
DeepSeek总结的MariaDB 的 DuckDB 存储引擎
数据库·mariadb
tiancaijiben2 小时前
阿里云VMware服务完全对接指南:从环境准备到混合云生产级应用
数据库
Curvatureflight3 小时前
MySQL 深分页越来越慢?从 LIMIT OFFSET 改成游标分页
数据库·oracle
XZ-0700013 小时前
MySQL事务
数据库·mysql·oracle