jilingxf的个人博客分享 http://blog.sciencenet.cn/u/jilingxf

博文

python 读取失去了server数据库并写入到excel

已有 2374 次阅读 2019-6-14 15:59 |个人分类:python|系统分类:科研笔记| python, sqlserver, excel

一个神奇的事情,公司居然使用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')




https://blog.sciencenet.cn/blog-853805-1184981.html

上一篇:mysql删除数据库中的所有表
下一篇:python 安装 出现0x80072f7d 错误
收藏 IP: 42.180.51.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-3-28 18:49

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部