• python操作MySQL数据库并将数据写入excel


    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    '''
    方法:通过pymsql模块连接mysql数据库,然后通过游标cursor查询SQL语句将结果存储在Excel文件中,其中Excel的生成使用xlwt实现的。
    作者:Mr' fan
    时间:2018年3月
    '''
    import pymysql
    import xlwt
    import datetime
    #def func():
    #连接mysql数据库。
    conn = pymysql.connect(host='127.0.0.1', port=6606, user='root', passwd='PxxxxxSH', db='nc', charset='utf8')
    #使用cursor()方法获取操作游标。
    cursor = conn.cursor()
    #effect_row = cursor.execute("select a.username,count(if(b.ntype='18060',true,null)),count(if(b.ntype='1001',true,null)) from nctermnetlog_if_201803 a,ncsnettype b where a.nettype=b.ntype and stime>unix_timestamp('2018-03-18 09:00:00') group by a.username")
    #使用execute方法执行SQL语句,并将统计结果存储在effect_row变量中。
    effect_row = cursor.execute("select a.username,a.mac,count(if(b.ntype='18060',true,null)),count(if(b.ntype='1001',true,null)),count(if(b.ntype='18079',true,null)),count(if(b.ntype='18080',true,null)),count(if(b.ntype='7633',true,null)),count(if(b.ntype='21368',true,null)),count(if(b.ntype='21400',true,null)),count(if(b.ntype='23581',true,null)),count(if(b.ntype='21416',true,null)) from nctermnetlog_if_201803 a,ncsnettype b where a.nettype=b.ntype and stime>unix_timestamp('2018-03-21 00:00:00') and stime<unix_timestamp('2018-03-22 00:00:00') group by a.username")
    print effect_row  #打印总行数
    #获取所有的记录结果
    row_3 = cursor.fetchall()
    #print row_3  #打印统计结果
    #获取上述SQL语句中的检索条件名称(将要成为Excel第一行的表头)。
    fields = cursor.description
    #将字段写入到EXCEL新表的第一行 。
    workbook = xlwt.Workbook(encoding='utf-8')
    #创建Excel中的一个sheet,并命名且为可重写状态。
    sheet = workbook.add_sheet('result_count',cell_overwrite_ok=True)
    #构造一个列表VnameList,用于将上述表头重命名,一定要一一对应。
    VnameList = [u"用户名","MAC",u"微信ID","QQ",u"新浪微博",u"腾讯微博",u"腾讯视频",u"京东商城",u"淘宝",u"今日头条",u"美团"]
    #将上述list中的虚拟身份依次填入Excel中去。
    for field in range(0,len(VnameList)):
    #sheet.write(0,field,fields[field][0])
    sheet.write(0,field,VnameList[field].encode("utf-8"))

    #根据横纵坐标依次录入查询到的信息值。
    row = 1
    col = 0
    for row in range(1,len(row_3)+1):
    for col in range(0,len(fields)):
    sheet.write(row,col,u'%s'%row_3[row-1][col])
    #格式化时间输出,用于给Excel起名时使用。
    sheet_time = datetime.datetime.now()
    book_mark = sheet_time.strftime('%Y%m%d')
    #将Excel文件保存下来
    workbook.save('./Count_result%s.xls'%book_mark.encode("utf-8"))
    #workbook.save(r'./Count_result.xls'.encode("utf-8"))
    #依次做提交和关闭操作。
    conn.commit()
    cursor.close()
    conn.close()

    #if __name__=="__main__":
    #  func()

  • 相关阅读:
    网易163邮箱被盗号找回经历
    C++中基类的析构函数为什么要用virtual虚析构函数
    像linux ls命令一样优雅地打印
    【Linux】- 六个超赞的字符画生成器
    linux欢迎界面 /etc/motd
    Linux 的 FIGlet 指令产生 ASCII Art 大型文字教学
    趣玩 Linux:四个生成字符图案(字符画)的命令
    案例参考手册-第四章 Curses字符界面.docx
    读取键盘输入流改为原始模式
    centos 7配置系统调度isolcpus(软中断绑定)
  • 原文地址:https://www.cnblogs.com/ddpeng/p/8645424.html
Copyright © 2020-2023  润新知