python 使用pymssql的基本总结

pymssql 的使用

python 中使用的第三方库
下载pymssql的文件,然后使用pip 命令下载。

连接数据库操作

class MSSQL:
    def __init__(self,host,user,pwd,db): #类的构造函数,初始化数据库连接ip或者域名,以及用户名,密码,要连接的数据库名称
        self.host=host
        self.user=user
        self.pwd=pwd
        self.db=db
    def __GetConnect(self):  #得到数据库连接信息函数, 返回: conn.cursor()
        self.conn=pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset='utf8')
        cur=self.conn.cursor()  #将数据库连接信息,赋值给cur。
        if not cur:
            raise(NameError,"连接数据库失败")
        else:
            return cur

    #执行查询语句,返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
    def ExecQuery(self,sql):  #执行Sql语句函数,返回结果
        cur = self.__GetConnect()   #获得数据库连接信息
        cur.execute(sql)  #执行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()

这段代码在我在网上找的,其中将基本操作封装在MSSQL类中,基本满足需求。

访问调用操作

一般从数据库获取数据可以使用简单sql语句,也可以使用存储过程。
在python中,使用字符串的拼接操作,我们一般在串中写%s%s,然后再使用变量访问。
简单sql语句

def reciveData():
    ms= MSSQL(host="127.0.0.1",user="sa",pwd="[email protected]",db="eduTable2017DB")  #实例化类对象,连接数据对象
    resOrganizationlist=ms.ExecQuery("SELECT organizationNo,businessTypeNo,organizationName  FROM eduTable2017DB.dbo.schoolBusinessRelation WHERE "
                                     "regionC='周至县'and businessTypeNo in('111','112','211','212','213','218','311','312','313','314','321','322','341','342','343','344','345')")
    return resOrganizationlist

存储过程

 strdatabase='exec [dbo].[P_20180122] @organizationNo ='+organizationNoValue+',@businessTypeNo='+businessTypeNoValue+',@dataType='+'学校'
 #strdatabase='exec [dbo].[P_20180122] @organizationNo =%s,@businessTypeNo=%s,@dataType=%s ',(organizationNoValue,businessTypeNoValue,'教师')
 list=ms.ExecQuery(strdatabase)

不知道为什么,第二种被屏蔽的不太符合要求,所以我改成了第一种方式进行访问,完美解决出错问题。欢迎指正!

猜你喜欢

转载自blog.csdn.net/u013266600/article/details/79136775
今日推荐