如何用Python对MySQL数据库进行增删改查
时间: 2024-12-11 13:19:43 浏览: 5
在Python中,我们可以使用`pymysql`库或者更推荐的`mysql-connector-python`库来连接和操作MySQL数据库。以下是一些基本的增删改查操作:
1. **连接数据库**:
```python
import mysql.connector
cnx = mysql.connector.connect(user='username', password='password',
host='localhost',
database='database_name')
cursor = cnx.cursor()
```
2. **插入数据(Insert)**:
```python
sql = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
val = ('value1', 'value2')
cursor.execute(sql, val)
cnx.commit() # 确认提交事务
```
3. **查询数据(Select)**:
```python
sql = "SELECT * FROM table_name WHERE condition"
cursor.execute(sql)
result = cursor.fetchall() # 获取所有结果
for row in result:
print(row)
```
4. **更新数据(Update)**:
```python
sql = "UPDATE table_name SET column1 = %s WHERE condition"
val = ('new_value',)
cursor.execute(sql, val)
cnx.commit()
```
5. **删除数据(Delete)**:
```python
sql = "DELETE FROM table_name WHERE condition"
cursor.execute(sql)
cnx.commit()
```
记得关闭游标和连接:
```python
cursor.close()
cnx.close()
```
阅读全文