Python連接MYSQL數據庫類
DBHelper.py:
import pymysql import logging import sys from mySQL.db_config import db_config # 加入日志 # 獲取logger實例 logger = logging.getLogger("baseSpider") # 指定輸出格式 formatter = logging.Formatter('%(asctime)s\ %(levelname)-8s:%(message)s') # 文件日志 file_handler = logging.FileHandler("operation_database.log") file_handler.setFormatter(formatter) # 控制台日志 console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(formatter) # 為logge添加具體的日志處理器 logger.addHandler(file_handler) logger.addHandler(console_handler) logger.setLevel(logging.INFO) class DBHelper(): # 構造函數,初始化數據庫連接 def __init__(self,sql,params=None): self.sql = sql self.params = params self.conn = None self.cur = None def connectiondatabase(self): print(db_config['host'],db_config['username'],db_config['password'],db_config['database'],db_config['charset']) try: self.conn = pymysql.connect(db_config['host'],db_config['username'], db_config['password'],db_config['database'],charset=db_config['charset']) except: logger.error("connectDatabase failed") return False self.cur = self.conn.cursor() return True # 關閉數據庫 def closedatabase(self): # 如果數據打開,則關閉;否則沒有操作 if self.conn and self.cur: self.cur.close() self.conn.close() return True # 執行數據庫的sq語句,主要用來做插入操作 def execute(self): self.connectiondatabase() try: if self.conn and self.cur: # 正常邏輯,執行sql,提交操作 self.cur.execute(self.sql,self.params) self.conn.commit() except: logger.error("execute failed: " + self.sql) logger.error("params: " + self.params) self.closedatabase() return False return True # 用來查詢表數據 def select(self): self.connectiondatabase() self.cur.execute(self.sql,self.params) result = self.cur.fetchall() print(result) return result
配置信息 db_config.py
db_config = { 'host':'127.0.0.1', 'port':3306, 'username':'root', 'password':'admin', 'database':'DataBase', 'charset':'utf8' }
測試代碼:
from mySQL import DBHelper as mdb def main(): # 連接 mysql,獲取連接的對象 SQL=r'SELECT * FROM TUsers' db=mdb.DBHelper(SQL) rows=db.select() # 依次遍歷結果集,發現每個元素,就是表中的一條記錄,用一個元組來顯示 for row in rows: print(row) if __name__ == '__main__': main()
