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

 

posted @ 2018-12-06 11:14  dongminglong  阅读(3792)  评论(0编辑  收藏  举报