zoukankan      html  css  js  c++  java
  • 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']))
  • 相关阅读:
    【训练】9.13 训练赛
    【训练】9.12 训练赛
    【题录】CF#666 Div.2
    【题解】JSOI2009球队收益 / 球队预算
    【申明】——暂别博客园——
    【题解】CF#896 D-Nephren Runs a Cinema
    【题解】洛谷P4707重返现世
    [HNOI2012][BZOJ2732] 射箭 [二分+半平面交]
    平面几何-学习笔记
    [NOI.AC省选模拟赛3.31] 星辰大海 [半平面交]
  • 原文地址:https://www.cnblogs.com/zldqpm/p/10857445.html
Copyright © 2011-2022 走看看