自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用 Python 實現(xiàn) MySQL 數(shù)據(jù)庫的 CRUD 操作并記錄日志

數(shù)據(jù)庫 MySQL
在開發(fā)基于數(shù)據(jù)庫的應(yīng)用程序時,對數(shù)據(jù)庫進行增刪改查(CRUD)操作是必不可少的一部分。Python 作為一門流行的編程語言,提供了多種方式與 MySQL 數(shù)據(jù)庫交互。

引言

在開發(fā)基于數(shù)據(jù)庫的應(yīng)用程序時,對數(shù)據(jù)庫進行增刪改查(CRUD)操作是必不可少的一部分。Python 作為一門流行的編程語言,提供了多種方式與 MySQL 數(shù)據(jù)庫交互。本文將向您展示如何通過 .ini 文件存儲 SQL 查詢,并使用 Python 的 mysql-connector-python 庫來執(zhí)行這些查詢。此外,我們還會集成日志功能,確保所有 SQL 操作都被記錄下來,便于后續(xù)審查和故障排除。

準備工作

首先,確保您的環(huán)境中已經(jīng)安裝了 mysql-connector-python 和 configparser 模塊??梢酝ㄟ^ pip 安裝:

pip install mysql-connector-python

創(chuàng)建配置文件

我們將創(chuàng)建兩個 .ini 文件來分別存放數(shù)據(jù)庫連接信息和 SQL 查詢語句。

db_config.ini - 數(shù)據(jù)庫連接信息

[mysql]
host=localhost
user=root
passwd=password
database=testdb

sql_queries.ini - SQL 查詢語句

[Queries]
create_employee = INSERT INTO employees (name, position, office, salary) VALUES (%s, %s, %s, %s)
read_employees = SELECT * FROM employees
update_employee_salary = UPDATE employees SET salary = %s WHERE id = %s
delete_employee = DELETE FROM employees WHERE id = %s

封裝數(shù)據(jù)庫操作

接下來,我們將創(chuàng)建一個名為 database_manager.py 的 Python 腳本,用以管理數(shù)據(jù)庫連接、讀取 SQL 查詢并執(zhí)行 CRUD 操作。同時,我們會添加日志記錄功能,確保每次 SQL 操作都被記錄到指定的日志文件中。

import configparser
import mysql.connector
from mysql.connector import Error
import logging
# 設(shè)置日志配置
logging.basicConfig(filename='database_operations.log', level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')
class DatabaseManager:
    def __init__(self, config_file='db_config.ini', sql_file='sql_queries.ini'):
        self.config = configparser.ConfigParser()
        self.sql_queries = configparser.ConfigParser()
        self.config.read(config_file)
        self.sql_queries.read(sql_file)
        self.connection = None
    def create_connection(self):
        """創(chuàng)建數(shù)據(jù)庫連接"""
        try:
            self.connection = mysql.connector.connect(
                host=self.config.get('mysql', 'host'),
                user=self.config.get('mysql', 'user'),
                passwd=self.config.get('mysql', 'passwd'),
                database=self.config.get('mysql', 'database')
            )
            print("連接到 MySQL 數(shù)據(jù)庫成功")
            logging.info("連接到 MySQL 數(shù)據(jù)庫成功")
        except Error as e:
            print(f"發(fā)生錯誤 '{e}'")
            logging.error(f"發(fā)生錯誤 '{e}'")
    def close_connection(self):
        """關(guān)閉數(shù)據(jù)庫連接"""
        if self.connection:
            self.connection.close()
            print("數(shù)據(jù)庫連接已關(guān)閉")
            logging.info("數(shù)據(jù)庫連接已關(guān)閉")
    def execute_query(self, query_name, data=None):
        """執(zhí)行 SQL 查詢并記錄日志"""
        cursor = self.connection.cursor()
        try:
            query = self.sql_queries.get('Queries', query_name)
            logging.info(f"執(zhí)行 SQL: {query} | 數(shù)據(jù): {data}")
            if data:
                cursor.execute(query, data)
            else:
                cursor.execute(query)
            self.connection.commit()
            print("查詢執(zhí)行成功")
            logging.info("查詢執(zhí)行成功")
        except Error as e:
            print(f"發(fā)生錯誤 '{e}'")
            logging.error(f"發(fā)生錯誤 '{e}'")
        finally:
            cursor.close()
    def fetch_data(self, query_name):
        """獲取數(shù)據(jù)并記錄日志"""
        cursor = self.connection.cursor(dictinotallow=True)
        try:
            query = self.sql_queries.get('Queries', query_name)
            logging.info(f"執(zhí)行 SQL: {query}")
            cursor.execute(query)
            result = cursor.fetchall()
            return result
        except Error as e:
            print(f"發(fā)生錯誤 '{e}'")
            logging.error(f"發(fā)生錯誤 '{e}'")
        finally:
            cursor.close()
# 示例用法:
if __name__ == "__main__":
    db_manager = DatabaseManager()
    db_manager.create_connection()
    # 插入新員工記錄
    employee_data = ('John Doe', 'Developer', 'London', 123000)
    db_manager.execute_query('create_employee', employee_data)
    # 讀取所有員工信息
    employees = db_manager.fetch_data('read_employees')
    for employee in employees:
        print(employee)
    # 更新員工薪資
    new_salary = (150000, 1)
    db_manager.execute_query('update_employee_salary', new_salary)
    # 刪除員工記錄
    employee_id = (1,)
    db_manager.execute_query('delete_employee', employee_id)
    db_manager.close_connection()

日志配置解釋

filename='database_operations.log':指定了日志輸出文件的位置。

level=logging.INFO:設(shè)置了日志級別為 INFO,意味著所有 INFO 級別及以上的消息(如 WARNING, ERROR)都會被記錄。

format='%(asctime)s - %(levelname)s - %(message)s':定義了日志的格式,包括時間戳、日志級別和消息內(nèi)容。

總結(jié)

通過以上步驟,我們可以輕松地使用 Python 來實現(xiàn) MySQL 數(shù)據(jù)庫的 CRUD 操作,并且所有的 SQL 操作都會被詳細地記錄下來。這種方式不僅簡化了代碼結(jié)構(gòu),還提高了應(yīng)用程序的可維護性和安全性。希望這篇文章能夠幫助您更好地理解和應(yīng)用 Python 進行數(shù)據(jù)庫操作!

Q: 如果我使用的是不同的數(shù)據(jù)庫,這段代碼還能用嗎?

A: 是的,但您需要根據(jù)所使用的數(shù)據(jù)庫類型調(diào)整連接字符串和可能的 SQL 語法。例如,如果您使用的是 PostgreSQL 或 SQLite,您應(yīng)該安裝相應(yīng)的 Python 驅(qū)動程序,并修改連接設(shè)置。

Q: 如何處理大型項目中的多個配置文件?

A: 對于大型項目,可以考慮使用環(huán)境變量或?qū)S玫呐渲霉芾硐到y(tǒng)來管理不同環(huán)境下的配置信息。這可以幫助避免敏感信息硬編碼在源代碼中,并提高部署靈活性。

希望這篇微信公眾號文章能夠滿足您的需求,清晰地展示了如何使用 Python 實現(xiàn) MySQL 數(shù)據(jù)庫的 CRUD 操作,并結(jié)合日志記錄功能確保操作透明度。

責任編輯:華軒 來源: 測試開發(fā)學(xué)習交流
相關(guān)推薦

2016-11-03 18:54:06

Java數(shù)據(jù)庫

2011-08-04 13:31:50

數(shù)據(jù)庫記錄更改日志觸發(fā)器

2010-05-28 10:48:52

MySQL數(shù)據(jù)庫

2019-01-02 09:30:59

MySQL數(shù)據(jù)庫日志審計

2010-07-07 17:05:39

SQL Server數(shù)

2009-06-04 15:59:53

Netbeans操作MMySQL數(shù)據(jù)庫

2010-06-01 17:45:57

MySQL數(shù)據(jù)庫

2021-08-02 09:01:29

PythonMySQL 數(shù)據(jù)庫

2017-11-27 11:41:06

python數(shù)據(jù)庫數(shù)據(jù)分析

2011-05-24 09:32:38

2024-03-25 07:22:50

GolangMySQL數(shù)據(jù)庫

2009-03-10 09:38:02

oraclepython數(shù)據(jù)庫

2010-05-28 14:51:47

MySQL數(shù)據(jù)庫

2022-09-01 23:29:22

MySQLPython數(shù)據(jù)庫

2024-09-29 16:11:55

NLogSQL數(shù)據(jù)庫

2010-06-02 16:57:50

MySQL數(shù)據(jù)庫同步

2024-09-02 00:27:51

SpringAOP自定義

2018-09-11 17:13:23

MySQ數(shù)據(jù)庫重復(fù)記錄

2021-08-02 10:53:28

PythonMySQL數(shù)據(jù)庫

2011-07-11 14:36:10

BinlogMysql
點贊
收藏

51CTO技術(shù)棧公眾號