python 3.6 链接mssql 进行数据操作

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import pymssql


class MSSQL(object):
    '''
    对pymssql的简单封装
    pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
    使用该库时,需要在Sql Server Configuration Manager里面将TCP/IP协议开启

    用法:
    '''

    def __init__(self,host,user,pwd,db):
        self.host=host
        self.user=user
        self.pwd=pwd
        self.db=db

    def GetConnect(self):
        '''
        得到链接信息
        :return: 
        '''
        if not self.db:
            raise (NameError,"没有设置数据库信息")
        self.connect=pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
        cur=self.connect.cursor()
        if not cur:
            raise (NameError,"链接数据库失败")
        else:
            return cur

    def ExecQuery(self,sql):
        '''
        执行查询语句
        返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段

        调用示例:
                ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
                resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
                for (id,NickName) in resList:
                    print str(id),NickName
        :param sql: sql语句
        :return: 
        '''
        cur=self.GetConnect()
        cur.execute(sql)
        resList = cur.fetchall()

        #查询完毕后必须关闭连接
        self.connect.close()
        return resList

    def ExecNonQuery(self, sql):
        """
        执行非查询语句

        调用示例:
            cur = self.__GetConnect()
            cur.execute(sql)
            self.conn.commit()
            self.conn.close()
        """
        cur = self.__GetConnect()
        cur.execute(sql)
        self.connect.commit()
        self.connect.close()

def test():
        ## ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
        ## #返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
        ## ms.ExecNonQuery("insert into WeiBoUser values('2','3')")

        ms = MSSQL(host="localhost", user="zl", pwd="zl@123456", db="zhongla20170901")
        resList = ms.ExecQuery("SELECT * FROM Pub_Law")
        print(resList)


if __name__ == '__main__':
    test()

  

posted @ 2017-11-02 17:42  eZplusy  阅读(700)  评论(0编辑  收藏  举报