python3操作sqlserver,查詢數據統計導出csv


 1 import  pymssql #導入sqlserver連接池模塊
 2 import csv      #導出csv文件使用模塊
 3 conn=pymssql.connect('服務器ip','用戶名','密碼','數據庫名')#連接數據庫
 4 cursor=conn.cursor() #打開數據庫連接池
 5 
 6 #執行sql命令
 7 cursor.execute('select interest from  Apply where interest is not null and interest<>%s',"非微信導入")
 8 
 9 #讀取數據
10 row=cursor.fetchone()
11 dicList={}
12 #循環讀取,直至讀完
13 while row:
14     #讀取第一列以,分割
15     str=row[0]
16     for item in str.split(','):
17           #判斷字典key里是否有該元素,有則加1,
18         if(item in dicList.keys()):
19 
20             dicList[item]=dicList[item]+1
21         #無該key則往字典里添加
22         else:
23 
24             dicList[item] =1
25 
26     row = cursor.fetchone()
27 #關閉連接池
28 cursor.close()
29 conn.close()
30 
31 
32 
33 with open("data.csv", "w", newline="") as datacsv:
34     # dialect為打開csv文件的方式,默認是excel,delimiter="\t"參數指寫入的時候的分隔符
35     csvwriter = csv.writer(datacsv, dialect=("excel"))
36     # csv文件插入一行數據,把下面列表中的每一項放入一個單元格(可以用循環插入多行)
37     for model in dicList:
38         csvwriter.writerow([model, dicList[model]])

 


免責聲明!

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



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