python3 操作sqlSever

Posted shaomine

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 操作sqlSever相关的知识,希望对你有一定的参考价值。

  相关代码如下:

  

技术分享图片
#coding =utf-8
import os
import pyodbc
import time
class SqlDb:


    def __init__(self, server=DESKTOP-94P70L6, database=ott, userid=sa, password=password):
        ‘‘‘‘‘ initialization ‘‘‘
        self.server = server
        self.database = database
        self.userid = userid
        self.password = password

    def __GetConnect(self):
        ‘‘‘‘‘ Connect to the DB ‘‘‘
        if not self.database:
            raise (NameError, "no setting db info")
        self.conn = pyodbc.connect(DRIVER={SQL Server Native Client 10.0}, SERVER=self.server, DATABASE=self.database, UID=self.userid,
                                   PWD=self.password, charset="UTF-8")
        # self.conn = "DRIVER={SQL Server Native Client 10.0};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s" % (self.server,self.database,self.userid,self.password)
        cur = self.conn.cursor()
        if not cur:
            raise (NameError, "connected failed!")
        else:
            return cur

    def ExecQuery(self, sql):
        ‘‘‘‘‘ Perform one Sql statement ‘‘‘
        cur = self.__GetConnect()
        cur.execute(sql)
        ret = cur.fetchall()
        cur.close()
        self.conn.close()
        return ret

    def ExecNoQuery(self, sql):
        ‘‘‘‘‘ Person one Sql statement like write data, or create table, database and so on‘‘‘
        cur = self.__GetConnect()
        cur.execute(sql)
        self.conn.commit()
        cur.close()
        self.conn.close()
View Code

 

以上是关于python3 操作sqlSever的主要内容,如果未能解决你的问题,请参考以下文章

scrapy主动退出爬虫的代码片段(python3)

scrapy按顺序启动多个爬虫代码片段(python3)

sqlsever收缩数据库日志操作

python常用代码片段总结

VS连接sqlsever数据库

VSCode自定义代码片段——git命令操作一个完整流程