python批量导出数据库多个表的数据

# --*-- coding:utf8 --*--
import pymysql, xlwt


def export_excel(table_name,sql):
# 连接数据库,查询数据
host, user, passwd, db = '数据库地址', '用户', '密码', '数据库名称'
conn = pymysql.connect(user=user, host=host, port=数据库端口号, passwd=passwd, db=db, charset='utf8')
cur = conn.cursor()
#sql = 'select * from %s' % table_name
cur.execute(sql) # 返回受影响的行数

fields = [field[0] for field in cur.description] # 获取所有字段名
all_data = cur.fetchall() # 所有数据

# 写入excel
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')

for col, field in enumerate(fields):
sheet.write(0, col, field)

row = 1
for data in all_data:
for col, field in enumerate(data):
sheet.write(row, col, field)
row += 1
book.save("C:/文件夹名称/%s.xls" %table_name)


if __name__ == '__main__':
table={
'EXCEL文件1': 'SELECT * FROM 表1',
'EXCEL文件2': 'SELECT * FROM 表2'
}
for table_name,sql in table.items():
export_excel(table_name,sql)
上一篇:golang反射reflect机制用法


下一篇:hive学习笔记之一:基本数据类型,Javaweb基础与实例教程