3实现的Mysql数据库操作封装类
时间: 2024-10-25 17:04:45 浏览: 7
Python3实现的Mysql数据库操作封装类
5星 · 资源好评率100%
在Python中,我们可以创建一个MySQL数据库操作的封装类,以便于管理和复用数据库连接、执行SQL语句等功能。下面是一个简单的例子:
```python
import pymysql
class MysqlDB:
def __init__(self, host='localhost', port=3306, user='', password='', db='', charset='utf8mb4'):
self.conn = None
self.cursor = None
self.host = host
self.port = port
self.user = user
self.password = password
self.db = db
self.charset = charset
self.connect()
def connect(self):
try:
self.conn = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.db,
charset=self.charset
)
self.cursor = self.conn.cursor()
except Exception as e:
print(f"Error connecting to MySQL: {e}")
def execute_query(self, sql, params=None):
try:
if params:
self.cursor.execute(sql, params)
else:
self.cursor.execute(sql)
return self.cursor.fetchall() or []
except Exception as e:
print(f"Error executing SQL: {sql}, Error: {e}")
return []
def close_connection(self):
if self.conn:
self.cursor.close()
self.conn.close()
# 使用示例
db = MysqlDB(host='localhost', user='root', password='password')
result = db.execute_query("SELECT * FROM table_name WHERE id = %s", (1,))
print(result)
db.close_connection()
```
这个`MysqlDB`类包含了初始化连接、执行查询、以及关闭连接的方法。通过实例化这个类,可以方便地对MySQL数据库进行操作。
阅读全文