时间: 2020-11-25|33次围观|0 条评论

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

 

转载于:https://www.cnblogs.com/dongml/p/10075623.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/98817216

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《python3操作sqlserver,查询数据统计导出csv
   

还没有人抢沙发呢~