Python结合Mysql可应用型的增删改查
时间: 2024-11-12 16:43:15 浏览: 5
python3 django+mysql+bootstrap增删改查
5星 · 资源好评率100%
在Python中,结合MySQL数据库进行数据操作通常使用SQLAlchemy或 pymysql等ORM(Object-Relational Mapping)库,它们能提供更高级别的接口,让开发者能够像操作Python对象一样处理数据库。以下是基本的增删改查操作:
1. **增加(Insertion)**:
- 导入所需的库如`pymysql`:
```python
import pymysql
```
- 连接到MySQL服务器:
```python
conn = pymysql.connect(host='localhost', user='username', password='password', db='your_database')
```
- 创建游标并执行插入语句:
```python
cursor = conn.cursor()
query = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
data = ('value1', 'value2')
cursor.execute(query, data)
conn.commit() # 提交事务
```
2. **删除(Deletion)**:
- 使用类似的方式执行删除查询,例如:
```python
delete_query = "DELETE FROM your_table WHERE condition"
cursor.execute(delete_query)
conn.commit()
```
3. **修改(Update)**:
- 更新记录也类似,比如更新某个id的数据:
```python
update_query = "UPDATE your_table SET column1 = %s WHERE id = %s"
new_data = ('new_value', 1)
cursor.execute(update_query, new_data)
conn.commit()
```
4. **查询(Selection)**:
- 查询数据通常通过SQL查询语句获取结果:
```python
select_query = "SELECT * FROM your_table WHERE condition"
cursor.execute(select_query)
results = cursor.fetchall() # 获取所有结果
for row in results:
print(row)
```
记得在操作完毕后关闭连接:
```python
cursor.close()
conn.close()
```
阅读全文