使用 Python 實(shí)現(xiàn) MySQL 數(shù)據(jù)庫(kù)的 CRUD 操作并記錄日志
引言
在開(kāi)發(fā)基于數(shù)據(jù)庫(kù)的應(yīng)用程序時(shí),對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查(CRUD)操作是必不可少的一部分。Python 作為一門(mén)流行的編程語(yǔ)言,提供了多種方式與 MySQL 數(shù)據(jù)庫(kù)交互。本文將向您展示如何通過(guò) .ini 文件存儲(chǔ) SQL 查詢(xún),并使用 Python 的 mysql-connector-python 庫(kù)來(lái)執(zhí)行這些查詢(xún)。此外,我們還會(huì)集成日志功能,確保所有 SQL 操作都被記錄下來(lái),便于后續(xù)審查和故障排除。
準(zhǔn)備工作
首先,確保您的環(huán)境中已經(jīng)安裝了 mysql-connector-python 和 configparser 模塊??梢酝ㄟ^(guò) pip 安裝:
pip install mysql-connector-python
創(chuàng)建配置文件
我們將創(chuàng)建兩個(gè) .ini 文件來(lái)分別存放數(shù)據(jù)庫(kù)連接信息和 SQL 查詢(xún)語(yǔ)句。
db_config.ini - 數(shù)據(jù)庫(kù)連接信息
[mysql]
host=localhost
user=root
passwd=password
database=testdb
sql_queries.ini - SQL 查詢(xún)語(yǔ)句
[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ù)庫(kù)操作
接下來(lái),我們將創(chuàng)建一個(gè)名為 database_manager.py 的 Python 腳本,用以管理數(shù)據(jù)庫(kù)連接、讀取 SQL 查詢(xún)并執(zhí)行 CRUD 操作。同時(shí),我們會(huì)添加日志記錄功能,確保每次 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ù)庫(kù)連接"""
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ù)庫(kù)成功")
logging.info("連接到 MySQL 數(shù)據(jù)庫(kù)成功")
except Error as e:
print(f"發(fā)生錯(cuò)誤 '{e}'")
logging.error(f"發(fā)生錯(cuò)誤 '{e}'")
def close_connection(self):
"""關(guān)閉數(shù)據(jù)庫(kù)連接"""
if self.connection:
self.connection.close()
print("數(shù)據(jù)庫(kù)連接已關(guān)閉")
logging.info("數(shù)據(jù)庫(kù)連接已關(guān)閉")
def execute_query(self, query_name, data=None):
"""執(zhí)行 SQL 查詢(xún)并記錄日志"""
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("查詢(xún)執(zhí)行成功")
logging.info("查詢(xún)執(zhí)行成功")
except Error as e:
print(f"發(fā)生錯(cuò)誤 '{e}'")
logging.error(f"發(fā)生錯(cuò)誤 '{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ā)生錯(cuò)誤 '{e}'")
logging.error(f"發(fā)生錯(cuò)誤 '{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è)置了日志級(jí)別為 INFO,意味著所有 INFO 級(jí)別及以上的消息(如 WARNING, ERROR)都會(huì)被記錄。
format='%(asctime)s - %(levelname)s - %(message)s':定義了日志的格式,包括時(shí)間戳、日志級(jí)別和消息內(nèi)容。
總結(jié)
通過(guò)以上步驟,我們可以輕松地使用 Python 來(lái)實(shí)現(xiàn) MySQL 數(shù)據(jù)庫(kù)的 CRUD 操作,并且所有的 SQL 操作都會(huì)被詳細(xì)地記錄下來(lái)。這種方式不僅簡(jiǎn)化了代碼結(jié)構(gòu),還提高了應(yīng)用程序的可維護(hù)性和安全性。希望這篇文章能夠幫助您更好地理解和應(yīng)用 Python 進(jìn)行數(shù)據(jù)庫(kù)操作!
Q: 如果我使用的是不同的數(shù)據(jù)庫(kù),這段代碼還能用嗎?
A: 是的,但您需要根據(jù)所使用的數(shù)據(jù)庫(kù)類(lèi)型調(diào)整連接字符串和可能的 SQL 語(yǔ)法。例如,如果您使用的是 PostgreSQL 或 SQLite,您應(yīng)該安裝相應(yīng)的 Python 驅(qū)動(dòng)程序,并修改連接設(shè)置。
Q: 如何處理大型項(xiàng)目中的多個(gè)配置文件?
A: 對(duì)于大型項(xiàng)目,可以考慮使用環(huán)境變量或?qū)S玫呐渲霉芾硐到y(tǒng)來(lái)管理不同環(huán)境下的配置信息。這可以幫助避免敏感信息硬編碼在源代碼中,并提高部署靈活性。
希望這篇微信公眾號(hào)文章能夠滿(mǎn)足您的需求,清晰地展示了如何使用 Python 實(shí)現(xiàn) MySQL 數(shù)據(jù)庫(kù)的 CRUD 操作,并結(jié)合日志記錄功能確保操作透明度。