pymysql 一個簡單的操作類

#!/usr/bin/python3.7
# -*- coding: UTF-8 -*-
'''
mysql  pymysql  class
func 基於 pymysql 的數據可以交互類,支持事務提交和回滾,返回結果記錄行數,和insert 的最新id
'''
import pymysql
CONNECT_TIMEOUT=100
conf = {'host':'localhost','port':3306,'user':'root','password':'root','timeout':CONNECT_TIMEOUT,'dbname':'test'}
class mysql_py():
    ## 定義構造方法,初始化參數
    def __init__(self):
        self.__conn = None
        self.__cursor = None
        self.lastrowid = None
        self.connect_timeout = conf['timeout']
        self.host = conf['host']
        self.port = conf['port']
        self.user = conf['user']
        self.password = conf['password']
        self.dbname = conf['dbname']
        self.rows_affected = 0


    ## 定義鏈接數據庫
    def __init_conn(self):
        try:
            conn = pymysql.connect(host=self.host,port=int(self.port),user=self.user,passwd=self.password,db=self.dbname,charset="utf8")
        except pymysql.Warning as e:
            raise pymysql.Warning(e)
        self.__conn = conn

    # 定義 句柄
    def __init_cursor(self):
        if self.__conn:
            self.__cursor = self.__conn.cursor()

    def close(self):
        if self.__conn:
            self.__conn.close()
            self.__conn = None
        if self.__cursor:
            self.__cursor.close()
            self.__cursor = None

    ## 處理select 語句
    def exec_selectsql(self,sql,args=None,fecth=0):
        try:
            if self.__conn is None:
                self.__init_conn()
                self.__init_cursor()
            if self.__cursor is None:
                self.__init_cursor()
            self.__conn.autocommit = True
            self.__cursor.execute(sql,args)
            self.rows_affected=self.__cursor.rowcount
            if fecth == 1:
                results = self.__cursor.fetchone()
            else:
                results = self.__cursor.fetchall()
            return results
        except pymysql.Error as e:
            raise pymysql.Error(e)
        finally:
            if self.__conn:
                self.close()
    # 處理 dml 語句 delete update insert
    def exec_txsql(self,sql,args=None):
        try:
            if self.__conn is None:
                self.__init_conn()
                self.__init_cursor()
            if self.__cursor is None:
                self.__init_cursor()
            if isinstance(args,list): ## isinstance 用於判斷變量類型
                self.rows_affected = self.__cursor.executemany(sql,args)
            else:
                self.rows_affected = self.__cursor.execute(sql,args)
            self.lastrowid = self.__cursor.lastrowid
            return self.rows_affected
        except pymysql.Error as e:
            raise pymysql.Error(e)
        finally:
            if self.__conn:
                self.close()


    # 動態拼接sql 調用 exec_txslq()方法執行操作
    def auto_joint_sql(self,table,data={},act="insert",where=None):
        if isinstance(data,dict):
            if act == "update":
                ## 更新操作
                # sql update table set a=%s,b=%s,c=%s where id=1
                field = ','.join('`' + k + '`=%s' for k in data.keys())
                argd = tuple(data.values())
                sql = "update "+table+ " set "+field
                if where is not None:
                    argsw = tuple(where.values())
                    where = ' and '.join('`' + k + '`=%s' for k in where.keys())

                    sql += " where "+ where
                    args = argd + argsw
            else:
                ## 插入操作
                ## sql = insert into table value(%s,%s,%s)
                ## args = ('fdf',323,3434)
                ## exceture(sql,args)
                val = ('%s',)*len(data)
                val = ','.join(val)
                keys = list(data.keys())
                keys = ','.join(keys)
                sql = "insert into "+table+'('+keys +') values('+val+')'

                args = tuple(data.values())

            return self.exec_txsql(sql,args)
        else:
            return "請輸入字典數據"


    ## 提交事務
    def exex_commit(self):
        try:
            if self.__conn:
                self.__conn.commit()
        except pymysql.Error as e:
            raise pymysql.Error(e)
        finally:
            if self.__conn:
                self.close()

    ## 回滾操作
    def exec_rollback(self):
        try:
            if self.__conn:
                self.__conn.rollback()
        except pymysql.Error as e:
            raise pymysql.Error(e)
        finally:
            if self.__conn:
                self.close()


    # 獲取插入記錄最後的主鍵id
    def get_lastrowid(self):
        return self.lastrowid

    # 獲取影響的行數
    def get_affectrows(self):
        return self.rows_affected
    # 實例銷燬之後,自動提交
    def __del__(self):
        self.exex_commit()


# 實例化類
conn = mysql_py()
# 查詢sql
sql = "select * from emoloyee where age > %s order by income"
args = (10,)
res = conn.exec_selectsql(sql,args)
print(res)

# 插入sql
sql = "insert into emoloyee(first_name,last_name,age,sex,income) values(%s,%s,%s,%s,%s)"
# 參數 插入1條用元組  插入多條用 列表
args = [('efdf','efdef',65,'M',7676),('efdf','efdef',65,'M',7676)]

res = conn.exec_txsql(sql,args)
print(res)

# 調用自動拼接sql
#
table="emoloyee"
# 數據要用 字典
data = {'first_name':'rrer',"last_name":'qqqtttq','age':28,'sex':'L','income':4543}
# 數據要用 字典
where = {'age':25,'sex':"L"}

res = conn.auto_joint_sql(table,data,'update',where)
print(res)

 

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