python3操作sqlserver,查询数据统计导出csv,, 1 import


 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]+121         #无该key则往字典里添加22         else:23 24             dicList[item] =125 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]])

python3操作sqlserver,查询数据统计导出csv

评论关闭