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()
相关推荐
a***976815 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
缺点内向15 小时前
Java: 在 Excel 中插入、提取或删除文本框
java·开发语言·excel
一 乐15 小时前
英语学习激励|基于java+vue的英语学习交流平台系统小程序(源码+数据库+文档)
java·前端·数据库·vue.js·学习·小程序
也许是_15 小时前
MySQL与PostgreSQL深度对比
数据库·mysql·postgresql
JIngJaneIL15 小时前
停车场管理|停车预约管理|基于Springboot+的停车场管理系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·notepad++·停车场管理|
钮钴禄·爱因斯晨16 小时前
Python常见的文件操作
android·数据库·python
CPU NULL16 小时前
Redis相关知识点总结
java·数据库·spring boot·redis·缓存
懒羊羊不懒@17 小时前
【MySQL | 进阶】存储引擎
数据库·mysql
YUJIANYUE17 小时前
查立得PHP+Mysql影院选座式教室座位预定系统 v1.0
开发语言·mysql·php
BD_Marathon17 小时前
Hive初始化元数据库时报错:Unknown version specified for initialization: 3.1.0
数据库·hive·hadoop