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']))
  • 相关阅读:
    excel文件导入mysql
    linux进程后台运行,且关终端后继续运行
    安装windows后grub修复
    华中科技大学 ubuntu14.04源
    Windows8.1远程桌面时提示凭据不工作的解决方案
    引文分析工具HistCite使用简介
    报账单打印
    iOS开发之--复制粘贴功能
    iOS学习之--字符串的删除替换(字符串的常用处理,删除,替换)
    iOS 裁剪View指定的角裁剪
  • 原文地址:https://www.cnblogs.com/zldqpm/p/10857445.html
Copyright © 2011-2022 走看看