用pymysql封装一个数据库类,包含数据库所有SQL操作
时间: 2023-09-18 08:07:17 浏览: 164
php操作mysql的封装类
以下是一个使用pymysql封装的数据库类,包含数据库的增删改查等操作:
```python
import pymysql
class Database:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database)
self.cursor = self.conn.cursor()
def __del__(self):
self.conn.close()
def execute_query(self, sql):
try:
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
except Exception as e:
print(f"Error executing query: {e}")
def execute_update(self, sql):
try:
self.cursor.execute(sql)
self.conn.commit()
print("Update successful")
except Exception as e:
self.conn.rollback()
print(f"Error updating database: {e}")
def execute_insert(self, sql):
try:
self.cursor.execute(sql)
self.conn.commit()
print("Insert successful")
except Exception as e:
self.conn.rollback()
print(f"Error inserting into database: {e}")
def execute_delete(self, sql):
try:
self.cursor.execute(sql)
self.conn.commit()
print("Delete successful")
except Exception as e:
self.conn.rollback()
print(f"Error deleting from database: {e}")
def select_all(self, table):
sql = f"SELECT * FROM {table}"
result = self.execute_query(sql)
return result
def select_by_id(self, table, id):
sql = f"SELECT * FROM {table} WHERE id={id}"
result = self.execute_query(sql)
return result
def insert(self, table, columns, values):
columns_str = ", ".join(columns)
values_str = ", ".join([f"'{value}'" for value in values])
sql = f"INSERT INTO {table} ({columns_str}) VALUES ({values_str})"
self.execute_insert(sql)
def update(self, table, id, columns, values):
set_clause = ", ".join([f"{column}='{value}'" for column, value in zip(columns, values)])
sql = f"UPDATE {table} SET {set_clause} WHERE id={id}"
self.execute_update(sql)
def delete(self, table, id):
sql = f"DELETE FROM {table} WHERE id={id}"
self.execute_delete(sql)
```
这个类包含了以下方法:
- `__init__(self, host, user, password, database)`:初始化连接数据库。
- `__del__(self)`:关闭数据库连接。
- `execute_query(self, sql)`:执行查询语句并返回结果。
- `execute_update(self, sql)`:执行更新语句。
- `execute_insert(self, sql)`:执行插入语句。
- `execute_delete(self, sql)`:执行删除语句。
- `select_all(self, table)`:查询表中所有数据。
- `select_by_id(self, table, id)`:按照id查询表中的数据。
- `insert(self, table, columns, values)`:向表中插入一条数据。
- `update(self, table, id, columns, values)`:更新表中的一条数据。
- `delete(self, table, id)`:删除表中的一条数据。
使用示例:
```python
db = Database("localhost", "root", "password", "test")
# 查询数据
result = db.select_all("users")
print(result)
# 插入数据
db.insert("users", ["name", "age"], ["Tom", 20])
# 更新数据
db.update("users", 1, ["name"], ["Jerry"])
# 删除数据
db.delete("users", 1)
```
阅读全文