python-mysql 实现插入一条数据再删除上一条数据
时间: 2024-05-03 13:17:06 浏览: 15
以下是使用 Python 和 MySQL 实现插入一条数据再删除上一条数据的示例代码:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
# 插入一条数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "记录插入成功。")
# 删除上一条数据
sql = "DELETE FROM customers WHERE customer_id = (SELECT MAX(customer_id) FROM customers)"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "记录已删除。")
```
这个示例代码连接到本地 MySQL 数据库,向 `customers` 表插入一条数据,然后再删除上一条数据。注意,这里删除上一条数据是通过 `SELECT MAX(customer_id) FROM customers` 获取表中最大的 `customer_id`,然后再删除对应的记录。因此,确保 `customer_id` 是自增的。如果不是,可以通过其他方式获取要删除的记录的主键。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)