import pymysqlclass MySQL: def __init__(self, host='localhost', port=3306, user='root', password='', database=None): self.host = host self.port = port self.user = user self.password = password self.database = database def __enter__(self): self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.database) return self def __exit__(self, exc_type, exc_val, exc_tb): self.conn.close() def select_all(self, table): with self.conn.cursor() as cursor: cursor.execute(f'select * from {table}') result = cursor.fetchall() return result def update(self, table, data, condition): with self.conn.cursor() as cursor: set_clause = ', '.join([f'{k}="{v}"' for k, v in data.items()]) cursor.execute(f'update {table} set {set_clause} where {condition}') self.conn.commit() return cursor.rowcount def delete(self, table, condition): with self.conn.cursor() as cursor: cursor.execute(f'delete from {table} where {condition}') self.conn.commit() return cursor.rowcount def insert(self, table, data): with self.conn.cursor() as cursor: keys = ', '.join(data.keys()) values = ', '.join([f'"{v}"' for v in data.values()]) cursor.execute(f'insert into {table} ({keys}) values ({values})') self.conn.commit() return cursor.lastrowid
时间: 2024-02-14 19:18:41 浏览: 148
python-mysql.zip_MYSQL_pymysql_python MySQL_python连接mysql_连接数据库
5星 · 资源好评率100%
好的,这是一个MySQL数据库操作类,具有基本的增删改查功能。您可以按照以下步骤进行测试:
1. 首先,您需要连接到MySQL数据库,可以使用以下代码:
```
with MySQL(host='localhost', user='root', password='your_password', database='your_database') as db:
# do something with db object
```
请将`your_password`和`your_database`替换为您的实际密码和数据库名称。
2. 接下来,您可以使用以下代码进行查询:
```
result = db.select_all('your_table_name')
print(result)
```
请将`your_table_name`替换为您的实际数据表名称。
3. 您可以使用以下代码进行更新操作:
```
data = {'column1': 'new_value1', 'column2': 'new_value2'}
condition = 'id=1'
rows_affected = db.update('your_table_name', data, condition)
print(f'{rows_affected} rows affected')
```
请将`column1`, `new_value1`, `column2`, `new_value2`和`your_table_name`替换为您的实际列名、新值和数据表名称。`condition`参数用于指定更新条件。
4. 您可以使用以下代码进行删除操作:
```
condition = 'id=1'
rows_affected = db.delete('your_table_name', condition)
print(f'{rows_affected} rows affected')
```
请将`your_table_name`替换为您的实际数据表名称。`condition`参数用于指定删除条件。
5. 最后,您可以使用以下代码进行插入操作:
```
data = {'column1': 'value1', 'column2': 'value2'}
last_insert_id = db.insert('your_table_name', data)
print(f'Last insert id: {last_insert_id}')
```
请将`column1`, `value1`, `column2`, `value2`和`your_table_name`替换为您的实际列名和值。插入操作将返回最后插入的行的ID。
阅读全文