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()
相关推荐
auspicious航10 分钟前
PostgreSQL统计信息:SQL调优的“眼睛”与基石
数据库·sql·postgresql
oradh36 分钟前
Oracle RMAN备份元数据管理
数据库·oracle·rman备份元数据管理·rman catalog
程序猿乐锅1 小时前
从 dsh 源码看「一切皆插件」与 Spring IoC
java·网络·数据库·人工智能·后端·spring
这就是佬们吗1 小时前
AI Agent 的四根支柱:LLM、工具、记忆与规划是如何协同的
大数据·数据库·人工智能
lq_bog1 小时前
spring事务失效
java·数据库·spring
人机(未转人工)1 小时前
Flask + MySQL + Ollama(DeepSeek) 漏洞资产库 的网络安全资产分析平台的templates中(chat.html)渲染文件
mysql·flask·html
词却1 小时前
数据库基础:MySQL 安装与基础操作
数据库·mysql
xieliyu.1 小时前
MySQL 进阶笔记:用户 / 会话 / 全局 / 局部变量 + CASE 分支语法
开发语言·数据库·笔记·mysql