1. 基本操作(增刪改查)封裝
2. 基於python3操作

1 ''' 2 Created on 2019年 3 數據庫工具類 4 @author: Root 5 ''' 6 import pymysql 7 import configparser 8 9 # 讀取配置文件 10 cf = configparser.ConfigParser() 11 cf.read('db.config') 12 host = cf.get('db', 'host') 13 port = cf.get('db', 'port') 14 port = int(port) 15 user = cf.get('db', 'user') 16 pwd = cf.get('db', 'passwd') 17 db = cf.get('db', 'db') 18 charset = cf.get('db', 'charset') 19 20 class DBUtils: 21 22 # 獲取數據庫連接 23 def getConn(self): 24 conn = pymysql.connect(host=host,port=port,user=user,passwd=pwd,db=db,charset=charset) 25 return conn 26 27 # 查詢所有數據 28 def get_allDate(self,sql): 29 # 取得連接 30 conn = DBUtils().getConn() 31 # 創建游標 32 cursor = conn.cursor() 33 # 執行SQL 34 cursor.execute(sql) 35 # 處理結果集 36 result = cursor.fetchall() 37 # 返回處理結果 38 return result 39 # 關閉連接 40 conn.close() 41 42 # 條件查詢 43 def get_dateByCount(self,sql,count): 44 # 取得連接 45 conn = DBUtils().getConn() 46 try: 47 # 創建游標 48 cursor = conn.cursor() 49 # 執行SQL 50 cursor.execute(sql,count) 51 # 處理結果集 52 result = cursor.fetchall() 53 # 返回處理結果 54 return result 55 except Exception as e: 56 print ('查詢失敗',e) 57 # 關閉連接 58 conn.close() 59 60 61 # 操作數據 62 def operate_dateByCount(self,sql,count): 63 # 取得連接 64 conn = DBUtils().getConn() 65 try: 66 # 創建游標 67 cursor = conn.cursor() 68 # 執行SQL 69 if type(count) is tuple: 70 cursor.execute(sql,count) 71 elif type(count) is list: 72 cursor.executemany(sql,count) 73 else: 74 print ('參數count類型不正確') 75 # 執行SQL成功,則提交事務 76 conn.commit() 77 print (count,'操作成功') 78 return 0 79 except Exception as e: 80 # 執行SQL失敗,則回滾事務 81 conn.rollback() 82 print ('操作失敗',e) 83 # 關閉連接 84 conn.close()
配置文件寫法
db.config或者db.ini
[db]
host=localhost
port=3306
user=root
passwd=root
db=xxx
charset=utf8