Python pymssql实现SQL Server数据库的增删改查

pymssql文档地址

http://www.pymssql.org/en/stable/

基本的增删改查

# -*- coding:utf-8 -*-

import pymssql

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()



#调用

if __name__ =="__main__":
    try:
        Ms=MSSQL(host=".0",user="sa",pwd="sa",db="test")
        reslist = Ms.ExecQuery("select * from webuser")#webuser 表名
        newsql = "update webuser set name='%s' where id=1" %u'测试'
        Ms.ExecNonQuery(newsql.encode('utf-8'))
    except Exception as e:
        print ('出错:%s'%e)

使用with语句(上下文管理器)

您可以将Python with语句与连接和游标一起使用。这使您不必显式关闭游标和连接。

with pymssql.connect(server, user, password, "tempdb") as conn:
    with conn.cursor(as_dict=True) as cursor:
        cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
        for row in cursor:
            print("ID=%d, Name=%s" % (row['id'], row['name']))

调用存储过程

with pymssql.connect(server, user, password, "tempdb") as conn:
    with conn.cursor(as_dict=True) as cursor:
        cursor.execute("""
        CREATE PROCEDURE FindPerson
            @name VARCHAR(100)
        AS BEGIN
            SELECT * FROM persons WHERE name = @name
        END
        """)
        cursor.callproc('FindPerson', ('Jane Doe',))
        for row in cursor:
            print("ID=%d, Name=%s" % (row['id'], row['name']))

猜你喜欢

转载自www.cnblogs.com/zldqpm/p/10857445.html