在 Python 中创建一个通用的数据库连接类,用于连接 MySQL 数据库并执行常见的数据库操作,可以提高代码的复用性和可维护性。下面是一个示例:
```python
import mysql.connector
class MySQLDatabase:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.connection = None
self.cursor = None
def connect(self):
try:
self.connection = mysql.connector.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database
)
self.cursor = self.connection.cursor()
print("Connected to MySQL database")
except mysql.connector.Error as error:
print(f"Error connecting to MySQL database: {error}")
def execute_query(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
print("Query executed successfully")
except mysql.connector.Error as error:
print(f"Error executing query: {error}")
def fetch_query(self, query):
try:
self.cursor.execute(query)
rows = self.cursor.fetchall()
return rows
except mysql.connector.Error as error:
print(f"Error fetching data: {error}")
return None
def close_connection(self):
if self.connection.is_connected():
self.cursor.close()
self.connection.close()
print("MySQL connection closed")
# Example of usage:
if __name__ == "__main__":
# Initialize MySQLDatabase object
db = MySQLDatabase(host="your_host",
user="your_username",
password="your_password",
database="your_database_name")
# Connect to the database
db.connect()
# Example query execution
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
)
"""
db.execute_query(create_table_query)
# Example data insertion
insert_query = """
INSERT INTO users (username, email)
VALUES ('john_doe', 'john@example.com')
"""
db.execute_query(insert_query)
# Example data retrieval
select_query = "SELECT * FROM users"
rows = db.fetch_query(select_query)
if rows:
for row in rows:
print(row)
# Close the database connection
db.close_connection()
```
在这个示例中:
- `MySQLDatabase` 类封装了 MySQL 数据库的连接和常用操作,包括连接、执行查询、执行插入操作以及关闭连接。
- `__init__` 方法用于初始化数据库连接参数。
- `connect` 方法用于建立数据库连接。
- `execute_query` 方法用于执行 SQL 查询或更新操作。
- `fetch_query` 方法用于执行查询并获取结果集。
- `close_connection` 方法用于关闭数据库连接。
根据自己的需求扩展这个类,添加更多的数据库操作方法或错误处理机制。记得替换示例中的 `your_host`、`your_username`、`your_password` 和 `your_database_name` 为实际的数据库连接信息。