【问题标题】:Python3 MySQLdb Query Does Not ExecutePython3 MySQLdb查询不执行
【发布时间】:2019-05-09 13:24:40
【问题描述】:

我在 Python3 中使用 MySQLdb 来执行一些查询。其中一个我有一个user_ids 列表,并希望根据它们从我的用户表中删除。

当我执行查询时,我收到来自 MySQLdb 的警告:

Warning: (1292, "Truncated incorrect DOUBLE value: '108, 114, 109, 115'")

试图执行的查询是:

DELETE FROM user
WHERE id IN (108, 114, 109, 115);

我的代码如下所示:

cur.execute(get_users)
users = cur.fetchall()
users = [item[0] for item in users]
users = ", ".join(str(user) for user in users)

cur.execute(delete_query, [users])

我也尝试执行以下操作,它不会导致任何警告但是检查我的数据库我仍然可以看到这些用户存在:

users = ", ".join("\'{}\'".format(user) for user in users)

以下内容可以完美运行,但并不安全: cur.execute(delete_query.format(users))

是的,我正在我的代码中执行db.commit()

【问题讨论】:

    标签: python-3.x mysql-python


    【解决方案1】:

    以下方法对我有用。 users 列表将直接进入 MySQL 驱动程序,因此注入不是问题:

    format_strings = ','.join(['%s'] * len(users))
    cursor.execute("DELETE FROM user WHERE id IN (%s)" % format_strings,
                    tuple(users))
    

    【讨论】:

    猜你喜欢
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 2015-01-18
    • 2012-12-04
    • 1970-01-01
    • 2011-12-06
    • 2021-09-10
    相关资源
    最近更新 更多