• 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']))
  • 相关阅读:
    Windows“神器”收集贴
    《SICP》读后感:关于软件本质的一点思考
    R语言apply函数族笔记
    论触摸板是比鼠标更先进的输入方式
    macbook上实现MacOS+Windows8+Ubuntu三系统
    使用Markdown+Pandoc+LaTex+Beamer制作幻灯片
    Python基本时间转换
    MySQL存储过程、触发器、自定义函数、事务
    Scrapy抓取jobbole数据
    win7安装scrapy
  • 原文地址:https://www.cnblogs.com/zldqpm/p/10857445.html
Copyright © 2020-2023  润新知