python mysql删除数据
时间: 2023-09-09 13:07:10 浏览: 93
要在Python中删除MySQL中的数据,可以使用以下步骤:
1. 导入MySQL连接器
```python
import mysql.connector
```
2. 连接到MySQL数据库
```python
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
3. 创建游标对象
```python
mycursor = mydb.cursor()
```
4. 编写SQL删除语句
```python
sql = "DELETE FROM yourtable WHERE some_column = some_value"
```
5. 执行SQL语句
```python
mycursor.execute(sql)
```
6. 提交更改
```python
mydb.commit()
```
完整代码示例:
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
sql = "DELETE FROM yourtable WHERE some_column = some_value"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
```
注意事项:
- 要删除所有行,请省略WHERE子句。
- 要删除整个表,请使用DROP TABLE语句。
阅读全文