|||
一个神奇的事情,公司居然使用sqlserver数据库,要做一些基本的查询,写了一点代码,查查都谁使用系统了。
闲言少叙,直接上代码 # -*- coding:utf-8 -*-
import pymssql import xlwt import datetime class MSSQL: def __init__(self,host,user,pwd,db): self.host = host self.user = user self.pwd = pwd self.db = db def __GetConnect(self): if not self.db: raise(NameError,"没有设置数据库信息") self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8") cur = self.conn.cursor() if not cur: raise(NameError,"连接数据库失败") else: return cur def ExecQuery(self,sql): cur = self.__GetConnect() cur.execute(sql) resList = cur.fetchall() #查询完毕后必须关闭连接 self.conn.close() return resList def ExecNonQuery(self,sql): cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close() ms = MSSQL(host="127.0.0.1",user="sa",pwd="sa",db="test") reslist = ms.ExecQuery(""" select sl.account AS 账户 ,wideIp AS IP ,mac AS 物理地址 ,SL.createTime AS 登录时间 ,sl.clientType from sys_LoginLog sl WHERE cast(SL.createTime as datetime) >cast('2019-05-31 00:00:00' as datetime) ORDER BY cast(SL.createTime as datetime) desc """) wbk = xlwt.Workbook() sheet = wbk.add_sheet('login') #第1行写入表头 sheet.write(0,0,'ID') sheet.write(0,1,'账户') sheet.write(0,2,'IP') sheet.write(0,3,'物理地址') sheet.write(0,4,'登录时间') sheet.write(0,5,'登录方式') j=1 for row in reslist: sheet.write(j,0,j)#第j行第int_col列写入第几行 int_col =1 for col in row: sheet.write(j,int_col,col)#第j行第int_col列写入内容 int_col+=1 j += 1 now_time = datetime.datetime.now() time_str = datetime.datetime.strftime(now_time,'%Y%m%d%H%M') wbk.save('test'+ time_str +'.xls')
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-12-14 12:59
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社