1. 程式人生 > >Python:MySQL資料操作類封裝

Python:MySQL資料操作類封裝

#!/usr/bin/env python
# coding:UTF-8


"""
@version: python3.x
@author:曹新健
@contact: [email protected]
@software: PyCharm
@file: dbSql.py
@time: 2018/9/22 17:47
"""

import pymysql
import logging
import sys

# 加入日誌
# 獲取logger例項
logger = logging.getLogger("dbSql")
# 指定輸出格式
formatter = logging.Formatter('%(asctime)s\
              %(levelname)-8s:%(message)s')
# 檔案日誌
file_handler = logging.FileHandler("dbSql.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 DbManager:
    # 建構函式
    def __init__(self, host='127.0.0.1',port=3306, user='cxj',
passwd='123456', db='cxjtest',charset='utf8'):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db
        self.charset = charset
        self.conn = None
        self.cur = None

    # 連線資料庫
    def connectDatabase(self):
        try:
            self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)
        except:
            logger.error("connectDatabase failed")
            return False
        self.cur = self.conn.cursor()
        return True

    # 關閉資料庫
    def close(self):
        # 如果資料開啟,則關閉;否則沒有操作
        if self.conn and self.cur:
            self.cur.close()
            self.conn.close()
        return True

    # 執行資料庫的sq語句,主要用來做插入操作
    def execute(self, sql,params=None,commit=False,):
        # 連線資料庫
        res = self.connectDatabase()
        if not res:
            return False
        try:
            if self.conn and self.cur:
                # 正常邏輯,執行sql,提交操作
                rowcount = self.cur.execute(sql, params)
                #print(rowcount)
                if commit:
                    self.conn.commit()
                else:
                    pass
        except:
            logger.error("execute failed: " + sql)
            logger.error("params: " + str(params))
            self.close()
            return False
        return rowcount

    # 查詢所有資料
    def fetchall(self, sql, params=None):
        res = self.execute(sql, params)
        if not res:
            logger.info("查詢失敗")
            return False
        self.close()
        results = self.cur.fetchall()
        logger.info("查詢成功" + str(results))
        return results

     # 查詢一條資料
    def fetchone(self, sql, params=None):
        res = self.execute(sql, params)
        if not res:
            logger.info("查詢失敗")
            return False
        self.close()
        result = self.cur.fetchone()
        logger.info("查詢成功" + str(result))
        return result

    # 增刪改資料
    def edit(self, sql,params=None):
        res = self.execute(sql,params,True)
        if not res:
            logger.info("操作失敗")
            return False
        self.conn.commit()
        self.close()
        logger.info("操作成功" + str(res))
        return res


if __name__ == '__main__':
    dbManager = DbManager()
    """
    sql = "select * from bandcard WHERE money>%s;"
    values = [1000]
    result = dbManager.fetchall(sql, values)
    """
    sql = "insert into bandcard values %s,%s,%s;"
    values = [(0, 100), (0, 200), (0, 300)]
    result = dbManager.edit(sql,values)