Python操作SQL Server類封裝

       最近用到Python,要操作數據庫,沒有現成的操作類,臨時寫了一個Python的SQLSERVER操作封裝類,分享一下,需要安裝pymssql包,安裝方法:https://blog.csdn.net/sinat_28984567/article/details/105316092,下邊是操作類:

# python sql server 操作類

import pymssql


class DBHelper:
    
    def __init__(self, host="127.0.0.1", port="1433", user="sa", password="123456", database="test"):  # 構造函數
        try:
            self.conn = pymssql.connect(host, user, password, database)
            self.cursor = self.conn.cursor()
        except Exception as e:
            print(e)

    # 返回執行execute()方法後影響的行數 

    def execute(self, sql):
        self.cursor.execute(sql)
        rowcount = self.cursor.rowcount
        return rowcount

    # 刪除並返回影響行數
    def delete(self, **kwargs):
        table = kwargs['table']

        where = kwargs['where']
        sql = 'DELETE FROM %s where %s' % (table, where)
        print(sql)
        try:
            # 執行SQL語句
            self.cursor.execute(sql)
            # 提交到數據庫執行
            self.conn.commit()
            # 影響的行數
            rowcount = self.cursor.rowcount
        except:
            # 發生錯誤時回滾
            self.conn.rollback()
        return rowcount

    # 新增並返回新增ID
    def insert(self, **kwargs):
        table = kwargs['table']
        del kwargs['table']
        sql = 'insert into %s(' % table
        fields = ""
        values = ""
        for k, v in kwargs.items():
            fields += "%s," % k
            values += "'%s'," % v
        fields = fields.rstrip(',')
        values = values.rstrip(',')
        sql = sql + fields + ")values(" + values + ")"
        print(sql)
        try:
            # 執行SQL語句
            self.cursor.execute(sql)
            # 提交到數據庫執行
            self.conn.commit()
            # 獲取自增id
            res = self.cursor.lastrowid
        except:
            # 發生錯誤時回滾
            self.conn.rollback()
        return res

    # 修改數據並返回影響的行數

    def update(self, **kwargs):
        table = kwargs['table']
        # del kwargs['table']
        kwargs.pop('table')
        where = kwargs['where']
        kwargs.pop('where')
        sql = 'update %s set ' % table
        for k, v in kwargs.items():
            sql += "%s='%s'," % (k, v)
        sql = sql.rstrip(',')
        sql += ' where %s' % where
        print(sql)
        try:
            # 執行SQL語句
            self.cursor.execute(sql)
            # 提交到數據庫執行
            self.conn.commit()
            # 影響的行數
            rowcount = self.cursor.rowcount
        except:
            # 發生錯誤時回滾
            self.conn.rollback()
        return rowcount

    # 查-一條條數據
    def selectTopone(self, **kwargs):
        table = kwargs['table']
        field = 'field' in kwargs and kwargs['field'] or '*'
        where = 'where' in kwargs and 'where ' + kwargs['where'] or ''
        order = 'order' in kwargs and 'order by ' + kwargs['order'] or ''
        sql = 'select top 1 %s from %s %s %s ' % (field, table, where, order)
        print(sql)
        try:
            # 執行SQL語句
            self.cursor.execute(sql)
            # 使用 fetchone() 方法獲取單條數據.
            data = self.cursor.fetchone()
        except:
            # 發生錯誤時回滾
            self.conn.rollback()
        return data

    # 查所有數據
    def selectAll(self, **kwargs):
        table = kwargs['table']
        field = 'field' in kwargs and kwargs['field'] or '*'
        where = 'where' in kwargs and 'where ' + kwargs['where'] or ''
        order = 'order' in kwargs and 'order by ' + kwargs['order'] or ''
        sql = 'select %s from %s %s %s ' % (field, table, where, order)
        print(sql)
        try:
            # 執行SQL語句
            self.cursor.execute(sql)
            # 使用 fetchone() 方法獲取單條數據.
            data = self.cursor.fetchall()
        except:
            # 發生錯誤時回滾
            self.conn.rollback()
        return data

       測試:

import pymssql
import MSSQL

conn = MSSQL.DBHelper('127.0.0.1', '1433', 'sa', '123456', 'test')

# insert測試
# cs = conn.insert(table="T1", Name="Python測試2", Sex="男")
# print(cs)

# delete 測試
# cs = conn.delete(table="T1", where="Id = 2")
# print(cs)

# update 測試
# cs = conn.update(table="T1", Name="Python測試3", Sex="man", where="Id in(1,2)")
# print(cs)

# select 測試
cs = conn.selectAll(table="T1", where="Name = 'Python測試3'")
print(cs)

       結果:

       以上就是操作類的內容,第一次寫歡迎指正。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章