写一个工具类连接rimysql
时间: 2023-07-25 09:09:10 浏览: 37
以下是连接rimysql的工具类示例代码,其中包括了连接数据库、执行SQL语句和关闭数据库连接等基本操作:
```python
import pymysql
class RiMySQL:
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.conn = None
self.cursor = None
def connect(self):
self.conn = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
self.cursor = self.conn.cursor()
def execute_sql(self, sql):
if not self.conn:
self.connect()
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
def close(self):
if self.cursor:
self.cursor.close()
if self.conn:
self.conn.close()
```
使用该工具类可以方便地连接rimysql数据库,并执行SQL语句。示例代码如下:
```python
mysql = RiMySQL('localhost', 3306, 'root', 'password', 'database_name')
mysql.connect()
result = mysql.execute_sql('SELECT * FROM table_name')
print(result)
mysql.close()
```
其中,需要替换对应的数据库连接信息和SQL语句。