【问题标题】:Passing variable into sql query in python (sqlite3)在python(sqlite3)中将变量传递给sql查询
【发布时间】:2017-05-25 00:22:27
【问题描述】:

我通过参数将值传递到查询中。问题是在运行以下代码时:

import sqlite3

def top10(restaurant):
    con = sqlite3.connect('example.db')
    cur = con.cursor()
    t = (restaurant,)
    cur.execute("SELECT * from orchard WHERE CUISINE_DESCRIPTION LIKE '%?%' ORDER BY SCORE;", t)
    return cur.fetchone()
print(top10("thai"))

我收到以下错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.

我不确定是什么触发了它。 当我嵌入一个名为 thai 的值而不是传入变量时,以下是成功运行的内容:

cur.execute("SELECT * from orchard WHERE CUISINE_DESCRIPTION LIKE '%thai%' ORDER BY SCORE;")

可能出了什么问题?

【问题讨论】:

    标签: sql database python-3.x sqlite


    【解决方案1】:

    试试这个

    cur.execute("SELECT * from orchard WHERE CUISINE_DESCRIPTION LIKE ? ORDER BY SCORE;", '%'+t+'%')
    

    【讨论】:

    • 这在将变量 t = (restaurant,) 转换为 t = ('%' + restaurant + '%',) 时有效,但在 sn-p 中的查询中执行此操作时无效
    猜你喜欢
    • 1970-01-01
    • 2016-07-26
    • 2019-11-03
    • 2017-09-10
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2016-05-19
    相关资源
    最近更新 更多