使用pymysql写一个实现数据增删改查的数据库接口
时间: 2024-03-14 09:46:54 浏览: 140
好的,以下是一个使用pymysql实现数据增删改查的数据库接口的示例代码:
```python
import pymysql
class Database:
def __init__(self):
self.conn = pymysql.connect(
host='localhost',
user='root',
password='password',
db='test_db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
self.cursor = self.conn.cursor()
def __del__(self):
self.conn.close()
def execute_query(self, query, params=None):
try:
self.cursor.execute(query, params)
self.conn.commit()
return self.cursor.fetchall()
except Exception as e:
self.conn.rollback()
raise e
def insert(self, table_name, data):
columns = ', '.join(data.keys())
values = ', '.join(['%s']*len(data))
query = f"INSERT INTO {table_name} ({columns}) VALUES ({values})"
self.execute_query(query, tuple(data.values()))
def update(self, table_name, data, condition):
set_values = ', '.join([f"{k}=%s" for k in data.keys()])
query = f"UPDATE {table_name} SET {set_values} WHERE {condition}"
self.execute_query(query, tuple(data.values()))
def delete(self, table_name, condition):
query = f"DELETE FROM {table_name} WHERE {condition}"
self.execute_query(query)
def select(self, table_name, columns=None, condition=None):
selected_columns = '*' if columns is None else ', '.join(columns)
query = f"SELECT {selected_columns} FROM {table_name}"
if condition is not None:
query += f" WHERE {condition}"
return self.execute_query(query)
```
使用示例:
```python
db = Database()
# 插入数据
data = {'name': '张三', 'age': 20, 'gender': '男'}
db.insert('students', data)
# 更新数据
data = {'name': '李四', 'age': 25}
condition = 'id=1'
db.update('students', data, condition)
# 删除数据
condition = 'id=2'
db.delete('students', condition)
# 查询数据
columns = ['name', 'age']
condition = 'gender="女"'
result = db.select('students', columns, condition)
print(result)
```
注意:以上代码只是一个示例,实际使用时需要根据具体情况进行修改。另外,为了安全起见,建议使用参数化查询来防止SQL注入攻击。
阅读全文