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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM