python连接mysql数据库通用类

在 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` 为实际的数据库连接信息。

相关推荐
jiayou641 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
于眠牧北1 天前
MySQL的锁类型,表锁,行锁,MVCC中所使用的临键锁
mysql
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
李广坤2 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时2 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构