当前位置: 首页 > article >正文

mysql数据库中多张表导出成excel方式

需求:
用于将mysql数据库中的几百张表导出成excel方式
表中有些字段的值是含有双引号和逗号值,比如json值
表中有些字段是汉字内容
导出的excel要求有表的列名
shell对于含有逗号和双引号的值会错乱分割
数据库中某些字段值是化学符号

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()

http://www.kler.cn/a/588685.html

相关文章:

  • Bash语言的集合
  • 【NLP】10. 机器学习模型性能评估指标(含多类别情况), ROC,PRC
  • 嵌入式Zephyr RTOS面试题及参考答案
  • Spring Boot Actuator 详解:让你的应用可监控、可管理、更健壮
  • Qt中的 #include “xxxx.moc“ 说明
  • vscode关闭仓库后如何打开
  • go数据结构笔记
  • Kotlin知识体系(一) : Kotlin的五大基础语法特性
  • SpiderX:专为前端JS加密绕过设计的自动化工具
  • Leetcode-2272. Substring With Largest Variance [C++][Java]
  • c++学习系列----002.写文件
  • 【C语言】动态内存管理用realloc管理更灵活
  • DeepSeek + Excel:数据处理专家 具体步骤
  • 蓝桥杯:山
  • 基于强化学习的智能路径规划系统
  • 腾龙T2000边缘计算网关:开启智能物联新时代
  • Excel ScriptLab学习笔记
  • 判断是不是二叉搜索树(C++)
  • Selenium 自动化测试学习总结
  • 不像人做的题————十四届蓝桥杯省赛真题解析(上)A,B,C,D题解析