Python实现增删改查
时间: 2024-12-27 18:10:51 浏览: 8
在Python中,实现数据库操作的"增删改查"通常涉及到数据库驱动程序,比如SQLite、MySQL、PostgreSQL等。以下是使用SQLAlchemy(一个Python ORM库)来操作数据的基本示例:
1. **添加(Insert)**:
```python
from sqlalchemy import create_engine, Table, insert
# 创建数据库引擎
engine = create_engine('sqlite:///example.db')
# 获取表对象
users_table = Table('users', metadata, autoload_with=engine)
# 插入数据
new_user = {'name': 'Alice', 'email': 'alice@example.com'}
ins = insert(users_table).values(new_user)
with engine.connect() as conn:
result = conn.execute(ins)
print(f'新用户插入成功,返回值:{result.lastrowid}')
```
2. **删除(Delete)**:
```python
delete_query = users_table.delete().where(users_table.c.name == 'Alice')
with engine.connect() as conn:
result = conn.execute(delete_query)
print(f'已删除 {result.rowcount} 条记录')
```
3. **修改(Update)**:
```python
update_query = users_table.update().where(users_table.c.id == 1).values(name='Bob')
with engine.connect() as conn:
result = conn.execute(update_query)
print(f'已更新 {result.rowcount} 条记录')
```
4. **查询(Select)**:
```python
select_query = users_table.select().where(users_table.c.email == 'bob@example.com')
with engine.connect() as conn:
rows = conn.execute(select_query).fetchall()
for row in rows:
print(row)
```
注意这只是一个基本示例,实际应用中可能需要处理更复杂的查询条件和事务管理。
阅读全文