用pymysql写一个数据库类,包含测试数据库,查询数据库等SQL操作
时间: 2024-05-15 22:20:04 浏览: 89
以下是一个基于pymysql的数据库操作类示例:
```python
import pymysql
class Database:
def __init__(self, host, port, user, password, db):
self.host = host
self.port = port
self.user = user
self.password = password
self.db = db
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,
db=self.db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
self.cursor = self.conn.cursor()
def close(self):
if self.cursor:
self.cursor.close()
if self.conn:
self.conn.close()
def execute(self, sql, params=None):
self.connect()
try:
self.cursor.execute(sql, params)
self.conn.commit()
except:
self.conn.rollback()
raise
finally:
self.close()
def query(self, sql, params=None):
self.connect()
try:
self.cursor.execute(sql, params)
result = self.cursor.fetchall()
except:
raise
finally:
self.close()
return result
```
使用示例:
```python
# 创建数据库实例
db = Database(host='localhost', port=3306, user='root', password='password', db='test')
# 执行SQL语句
db.execute("INSERT INTO `users` (`name`, `age`) VALUES ('Alice', 25)")
# 查询数据
result = db.query("SELECT * FROM `users` WHERE `age` > %s", (20,))
for row in result:
print(row)
```
在此示例中,使用了connect()和close()方法来连接和关闭数据库连接,execute()和query()方法用于执行SQL语句和查询数据。其中execute()方法会自动提交事务,而query()方法不会。这个类可以根据需要进行扩展,例如添加更多的查询方法、事务处理等。
阅读全文