一次Python操作数据库和excel过程

时间:2019-11-01
本文章向大家介绍一次Python操作数据库和excel过程,主要包括一次Python操作数据库和excel过程使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

师从‘百测’besttest

  最近牛大湿教了操作数据库和操作excel,写了一个小小的脚本,传入一个表名后,将表中所有数据写入excel中。

  使用了pymysql,xlwt,需要自行安装。

import pymysql,xlwt
def sql_into_excel(table_name):
        db_info = {'user': 'xxx', 'password': '123456','host': '8.8.8.8', 'db': 'asd', 'port': 3306, 'charset': 'utf8','autocommit': True}
        conn = pymysql.connect(**db_info)  # 建立连接
        cur = conn.cursor(pymysql.cursors.DictCursor) #获取表头的游标

        sql = 'select * from %s' %(table_name) #如果参数在实际查询中需要用‘’,在SQL中写法:'%s'
        cur.execute(sql)
        all = cur.fetchall()

        cur.close()
        conn.close()

        key = []
        for i in all[0]:
                key.append(i)

        book = xlwt.Workbook()
        sheet = book.add_sheet('sheet1')

        for j in range(len(key)):
                sheet.write(0,j,key[j])
                for x in range(len(all)):
                        a = key[j]
                        sheet.write(x+1,j,all[x][a])

        book.save('test.xls')

sql_into_excel('table_name')

原文地址:https://www.cnblogs.com/shengqi/p/11776087.html