Python3基於PyMySQL封裝的常用操作基礎類庫
阿新 • • 發佈:2022-03-17
db_host = "localhost" db_user = "root" db_pass = "root" db_name = "test" db_port = 3306 db_charset = "utf8"
# -*- coding: utf-8 -*- """Python連線到 MySQL 資料庫及相關操作(基於Python3)""" import pymysql.cursors import dbconfig as dbconfig class Database: """ Python連線到 MySQL 資料庫及相關操作 """ """ Created by: https://blog.csdn.net/yyykj/article/details/103053719""" """ Upgraded by: https://github.com/felixwann """ """ conf: 類引數,資料庫的連線引數配置字典,含host、port、user、pw、db、charset(可選,預設utf8) connected: 屬性,True資料庫連線成功,False連線失敗 insert(self, table, val_obj): 方法,插入資料到資料表 table: 資料表名稱 val_obj: 待插入資料的欄位名和值的鍵值對字典 返回: 成功則返回新插入資料的主鍵ID,失敗返回False update(self, table, val_obj, range_str): 方法,更新資料表中的資料 table: 資料表名稱 val_obj: 待更新資料的欄位名和值的鍵值對字典 range_str: 更新範圍的條件語句字串 返回: 成功返回更新的行數,失敗返回False delete(self, table, range_str): 方法,在資料表中刪除資料 table: 資料表名稱 range_str: 刪除範圍的條件語句字串 返回: 成功返回刪除的行數,失敗返回False select_one(self, table, factor_str, field='*'): 方法,查詢表中符合條件唯一的一條資料 table: 資料表名稱 factor_str: 查詢唯一條件語句字串 field: 查詢結果返回哪些欄位,多個用逗號分隔,可選引數,預設返回所有欄位 返回: 成功返回一條資料的欄位名與值的一維字典,失敗返回False select_more(self, table, range_str, field='*'): 方法,查詢表中符合條件的所有資料 table: 資料表名稱 range_str: 查詢條件語句字串 field: 查詢結果返回哪些欄位,多個用逗號分隔,可選引數,預設返回所有欄位 返回: 成功返回多條資料的欄位名與值的二維字典,失敗返回False count(self, table, range_str='1'): 方法,統計資料表中符合條件的總函式 table: 資料表名稱 range_str: 查詢條件語句字串,可選引數,預設表中所有行數 返回: 成功返回符合條件的行數,失敗返回False sum(self, table, field, range_str='1'): 方法,對資料表中某數值型別欄位求和 table: 資料表名稱 field: 需要求和的欄位,可以是多個欄位的計算公式 range_str: 需要求和的條件語句字串,可選引數,預設表中所有行 返回: 成功返回求和結果,失敗返回False close(self): 方法,關閉資料庫連線,物件銷燬時也會自動關閉,所以多數時候不用特意呼叫""" connected = False __conn = None # 建構函式,初始化時直接連線資料庫 def __init__(self): conf = { "host": dbconfig.db_host, "user": dbconfig.db_user, "password": dbconfig.db_pass, "database": dbconfig.db_name, "port": int(dbconfig.db_port),"charset": dbconfig.db_charset } if type(conf) is not dict: print('錯誤: 引數不是字典型別!') else: for key in ['host', 'port', 'user', 'password', 'database']: if key not in conf.keys(): print('錯誤: 引數字典缺少 %s' % key) if 'charset' not in conf.keys(): conf['charset'] = 'utf8' try: self.__conn = pymysql.connect( host=conf['host'], port=conf['port'], user=conf['user'], passwd=conf['password'], db=conf['database'], charset=conf['charset'], cursorclass=pymysql.cursors.DictCursor) self.connected = True except pymysql.Error as e: print('資料庫連線失敗:', end='') # 插入資料到資料表 def insert(self, table, val_obj): sql_top = 'INSERT INTO ' + table + ' (' sql_tail = ') VALUES (' for key, val in val_obj.items(): sql_top += '`' + key + '`' + ',' val = "'" + val + "'" if type(val) == str else val sql_tail += val + ',' sql = sql_top[:-1] + sql_tail[:-1] + ')' try: with self.__conn.cursor() as cursor: cursor.execute(sql) self.__conn.commit() return cursor.lastrowid except pymysql.Error as e: self.__conn.rollback() return {e, sql} def insert_many(self, table, params, all_data): sql_top = 'INSERT INTO ' + str(table) + ' (' sql_tail = ') VALUES (' for val in params: sql_top += '`' + str(val) + '`' + ',' # val = "'" + val + "'" if type(val) == str else val sql_tail += str('%s') + ',' sql = sql_top[:-1] + sql_tail[:-1] + ')' try: # return {sql, all_data} with self.__conn.cursor() as cursor: flag = cursor.executemany(sql, all_data) self.__conn.commit() return flag except pymysql.Error as e: self.__conn.rollback() print({e, sql}) return {e, sql} # 更新資料到資料表 def update(self, table, val_obj, range_str): sql = 'UPDATE ' + table + ' SET ' for key, val in val_obj.items(): val = "'" + val + "'" if type(val) == str else val sql += key + '=' + val + ',' sql = sql[:-1] + ' WHERE ' + range_str try: with self.__conn.cursor() as cursor: cursor.execute(sql) self.__conn.commit() return cursor.rowcount except pymysql.Error as e: self.__conn.rollback() return False # 刪除資料在資料表中 def delete(self, table, range_str): sql = 'DELETE FROM ' + table + ' WHERE ' + range_str try: with self.__conn.cursor() as cursor: cursor.execute(sql) self.__conn.commit() return cursor.rowcount except pymysql.Error as e: self.__conn.rollback() return False # 查詢唯一資料在資料表中 def select_one(self, table, factor_str, field='*'): sql = 'SELECT ' + field + ' FROM ' + table + ' WHERE ' + factor_str try: with self.__conn.cursor() as cursor: cursor.execute(sql) self.__conn.commit() return cursor.fetchone() except pymysql.Error as e: return False # 查詢多條資料在資料表中 def select_more(self, table, range_str, field='*'): sql = 'SELECT ' + field + ' FROM ' + table + ' WHERE ' + range_str try: with self.__conn.cursor() as cursor: cursor.execute(sql) self.__conn.commit() return cursor.fetchall() except pymysql.Error as e: return False # 統計某表某條件下的總行數 def count(self, table, range_str='1'): sql = 'SELECT count(*)res FROM ' + table + ' WHERE ' + range_str try: with self.__conn.cursor() as cursor: cursor.execute(sql) self.__conn.commit() return cursor.fetchall()[0]['res'] except pymysql.Error as e: return False # 統計某欄位(或欄位計算公式)的合計值 def sum(self, table, field, range_str='1'): sql = 'SELECT SUM(' + field + ') AS res FROM ' + table + ' WHERE ' + range_str try: with self.__conn.cursor() as cursor: cursor.execute(sql) self.__conn.commit() return cursor.fetchall()[0]['res'] except pymysql.Error as e: return False def query(self, sql): try: with self.__conn.cursor() as cursor: cursor.execute(str(sql)) self.__conn.commit() return cursor.fetchall() except pymysql.Error as e: print(str(e)) return False # 銷燬物件時關閉資料庫連線 def __del__(self): try: self.__conn.close() except pymysql.Error as e: pass # 關閉資料庫連線 def close(self): self.__del__()