我正在try 从我的数据库中删除一行,但没有成功.以下是我的代码:

import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="user",passwd="1",database="workers")
mycursor = mydb.cursor()
query = "DELETE FROM `workers` WHERE id = %s"
# connect to the database server
# execute the query
mycursor.execute(query, (1,)) 
mysql.commit()  # You need to commit the transaction

注意:我使用的是python3.10,操作系统是ubuntu.我也try 使用%d而不是%s,但它不工作.

推荐答案

我创建了一个测试表:

mysql> select version();
+-----------+
| version() |
+-----------+
| 8.2.0     |
+-----------+

mysql> create table workers (id serial primary key);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into workers values (1), (2);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from workers;
+----+
| id |
+----+
|  1 |
|  2 |
+----+

DEMO脚本DELETE-Test.py:

import mysql.connector

if __name__ == '__main__':
    config = { ... }

    mydb = mysql.connector.connect(**config)
    mycursor = mydb.cursor()

    # FIXED: use %s instead of %d
    query = "DELETE FROM `workers` WHERE id = %s"

    mycursor.execute(query, (1,))

    # FIXED: mydb instead of mysql 
    mydb.commit()

    mycursor.close()
    mydb.close()

运行脚本:

% python3 --version
Python 3.11.4
% python3 ./delete-test.py
%

判断结果:

mysql> select * from workers;
+----+
| id |
+----+
|  2 |
+----+

Mysql相关问答推荐

无法删除或更新父行:外键约束无法删除表

在MySQL中查找包含无效正则表达式的行

mysql 获取每个单词的第一个字母

MySQL中如何对字符串进行算术运算?

使用不同的 where 列进行子 Select

没有 ORDER BY 的查询性能很高,有 ORDER BY 的查询速度慢得像爬行一样

Golang中使用Gorm的Where条件转义字符无法正常工作的问题

如何在Mysql中使用With和Values

for each 查询设置 MySQL @@session.time_zone 而不是 CONVERT_TZ 的缺点?

SQL: Select TEXT 字段的子字符串比整个值快

为什么 ORDER BY 'id' 'desc' 不返回语法错误?

动态创建内联 SQL 表(用于排除左连接)

提高mysql导入速度

MySQL 工作台与 phpMyAdmin

当您无法修复表时,如何修复 MySQL不正确的密钥文件错误?

错误 1396 (HY000): 'user'@'localhost' 的操作 DROP USER 失败

在 PHP/MySQL 中将日期时间存储为 UTC

在 Mac 上设置 Laravel php artisan migrate 错误:没有这样的文件或目录

MySQL获取两个值之间的随机值

如何从命令行调用带有参数的mysql存储过程?