pymysql增删改查
时间: 2024-08-15 15:00:32 浏览: 48
`pymysql`是一个Python的MySQL数据库连接模块,它允许开发者在Python程序中方便地操作MySQL数据库。下面是一些基本的增删改查操作:
1. **插入数据(Insert)**:
```python
import pymysql
conn = pymysql.connect(host='localhost', user='username', password='password', db='database_name')
cursor = conn.cursor()
query = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
values = ('value1', 'value2')
cursor.execute(query, values)
conn.commit() # 提交事务
cursor.close()
conn.close()
```
2. **删除数据(Delete)**:
```python
cursor.execute("DELETE FROM table_name WHERE condition")
conn.commit()
```
`condition`是你想要删除的数据满足的特定条件。
3. **更新数据(Update)**:
```python
query = "UPDATE table_name SET column1=%s, column2=%s WHERE some_column=%s"
values = ('new_value1', 'new_value2', 'some_condition')
cursor.execute(query, values)
conn.commit()
```
4. **查询数据(Select)**:
```python
query = "SELECT * FROM table_name WHERE condition"
cursor.execute(query)
results = cursor.fetchall() # 获取所有结果
for row in results:
print(row)
```
记得处理好每个操作后的连接关闭,以及异常处理,例如检查`cursor.execute()`是否成功返回影响行数等。
阅读全文