Python工具類(一)—— 操作Mysql數據庫


 

如何調用直接看__main__函數里如何調用此工具類就闊以啦!

  1 # encoding=utf-8
  2 import pymysql
  3 
  4 # 導入所有Mysql配置常量,請自行指定文件
  5 from conf.settings import *
  6 
  7 
  8 class MysqlConnection(object):
  9     """
 10     mysql操作類,對mysql數據庫進行增刪改查
 11     """
 12 
 13     def __init__(self, config):
 14         # Connect to the database
 15         self.connection = pymysql.connect(**config)
 16         self.connection.autocommit(True)
 17         self.cursor = self.connection.cursor()
 18 
 19     def QueryAll(self, sql):
 20         """
 21         查詢所有數據
 22         :param sql:
 23         :return:
 24         """
 25         # 數據庫若斷開即重連
 26         self.reConnect()
 27 
 28         self.cursor.execute(sql)
 29         return self.cursor.fetchall()
 30 
 31     def QueryMany(self, sql, n):
 32         """
 33         查詢某幾條數據數據
 34         :param sql:
 35         :return:
 36         """
 37         # 數據庫若斷開即重連
 38         self.reConnect()
 39 
 40         self.cursor.execute(sql)
 41         return self.cursor.fetchmany(n)
 42 
 43     def QueryOne(self, sql):
 44         """
 45         查詢某幾條數據數據
 46         :param sql:
 47         :return:
 48         """
 49         # 數據庫若斷開即重連
 50         self.reConnect()
 51 
 52         self.cursor.execute(sql)
 53         return self.cursor.fetchone()
 54 
 55     # return self.cursor.fetchone()
 56 
 57     def reConnect(self):
 58         """
 59         重連機制
 60         :return:
 61         """
 62         try:
 63             self.connection.ping()
 64         except:
 65             self.connection()
 66 
 67     def Operate(self, sql, params=None, DML=True):
 68         """
 69         數據庫操作:增刪改查
 70         DML: insert / update / delete
 71         DDL: CREATE TABLE/VIEW/INDEX/SYN/CLUSTER
 72         """
 73         try:
 74             # 數據庫若斷開即重連
 75             self.reConnect()
 76 
 77             with self.connection.cursor() as cursor:
 78                 cursor.execute(sql, params)
 79 
 80                 self.connection.commit()
 81 
 82         except Exception as e:
 83             if DML:
 84                 # 涉及DML操作時,若拋異常需要回滾
 85                 self.connection.rollback()
 86             print(e)
 87 
 88     def __del__(self):
 89         """
 90         MysqlConnection實例對象被釋放時調用此方法,用於關閉cursor和connection連接
 91         """
 92         self.cursor.close()
 93         self.connection.close()
 94 
 95 
 96 if __name__ == "__main__":
 97     # 初始化MysqlConnection實例對象需要傳Mysql配置信息的字典
 98     config = {'host': MYSQL_HOST, 'charset': CHARSET, 'db': DB, 'user': USER, 'port': MYSQL_PORT, 'password': PASSWORD}
 99     msc = MysqlConnection(config)
100     sql = "delete from users where username ='%s'" % "123456"
101 
102     print(msc.Operate(sql))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM