【问题标题】:Python mysql using variable to select a certain fieldPython mysql使用变量选择某个字段
【发布时间】:2015-07-31 16:56:23
【问题描述】:

在使用 python 和 mysql 时遇到了一些棘手的问题。为简单起见,以下代码返回变量“field”中的任何内容,它是一个字符串。例如“用户名”或“密码”。

options = [field, userID]
entries = cursor.execute('select (?) from users where id=(?)', options).fetchall()
print(entries);

如果我删除第一个 (?) 并只使用实际名称(如“用户名”),则此代码可以正常工作。谁能提供一些意见?

【问题讨论】:

    标签: python mysql select field


    【解决方案1】:

    您的查询实际上是这样形成的:

    select "field" from users where id="value"
    

    它会返回一个字符串“字段”而不是实际的表字段值。

    您不能参数化列名和表名 (docs):

    参数占位符只能用于插入列值。他们 不能用于 SQL 的其他部分,例如表名, 声明等。

    对该部分使用字符串格式:

    options = [userID]
    query = 'select {field} from users where id=(?)'.format(field=field)
    cursor.execute(query, options).fetchall()
    

    更多解释的相关主题:

    【讨论】:

    • 安全性怎么样?
    • @NikolayShindarov 在这种情况下,额外的预验证/转义的责任在于代码的作者。
    猜你喜欢
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多