使用python的pymysql库写一个mysql工具类
时间: 2024-05-13 15:14:45 浏览: 9
好的,以下是一个简单的MySQL工具类,使用Python的pymysql库实现:
```python
import pymysql
class MySQLTool:
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.connection = None
def connect(self):
self.connection = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
def disconnect(self):
if self.connection is not None:
self.connection.close()
def execute(self, sql, params=None):
cursor = self.connection.cursor()
cursor.execute(sql, params)
result = cursor.fetchall()
cursor.close()
return result
```
使用方法:
```python
tool = MySQLTool("localhost", 3306, "root", "password", "test_db")
tool.connect()
result = tool.execute("SELECT * FROM users WHERE age > %s", (18,))
print(result)
tool.disconnect()
```
以上代码中,MySQLTool类的构造函数接受MySQL连接所需的参数,并且提供了连接、断开连接和执行SQL语句的方法。execute方法接受一个SQL查询语句和一个参数元组,然后返回查询结果。在使用该工具类时,需要先调用connect方法连接到数据库,然后执行SQL查询,最后调用disconnect方法断开连接。