【问题标题】:Python: sqlite3 parametrized query gets no resultsPython:sqlite3 参数化查询没有结果
【发布时间】:2017-10-21 02:47:49
【问题描述】:

我尝试使用参数化查询从表中选择条目。他们不返回任何结果。代码如下:

var = str.capitalize(var)
selected = db.execute('select a, b, c from table1 where a=(?)', [var])

var始终是三个小写字符串(例如'xxx'),'a'列是数据库中的TEXT类型,包含三个大写字符串(例如'XXX')。

我也尝试了可怕的:

selected = db.execute('select a, b, c from table1 where a="%s"' % str.capitalize(var)])

因为我认为execute方法省略引号是一个问题,但它也不起作用。唯一让我得到任何结果的是:

selected = db.execute('select a, b, c from table1 where a="XXX"')

我在 Windows 10 上使用 Python 3.6.0,有人 here 建议这可能是一个问题,但他们的解决方案也对我不起作用。

【问题讨论】:

  • 能分享几行表格吗
  • 38 英镑 2017-02-24 5.1011 39 英镑 2017-02-27 5.0646 40 英镑 2017-02-28 5.0617
  • a、b、c 是哪一列? var 包含什么?
  • 列是 (id, a, b, c),var 是通过 POST 请求从表单中获取的,并且总是像 'gbp'、'usd'、'jpy'。
  • 我猜你对capitalize()upper()感到困惑

标签: python sqlite sql-parametrized-query


【解决方案1】:

capitalize 仅将第一个字母转换为大写字母。要将所有内容转换为大写字母,请使用 upper()

参数必须作为元组/字典传递

使用

selected = db.execute('select a, b, c from table1 where a=?', (var.upper(),))

或者

selected = db.execute('select a, b, c from table1 where a=:var', {"var":var.upper()})

阅读更多here

【讨论】:

    【解决方案2】:

    您必须使用upper 将其转换为全部大写,试试这个:

    var = var.upper()
    selected  =  db.execute('select a, b, c from table1 where a=?', (var,))
    

    这个也可以:

    var = var.upper()
    selected = db.execute('select a, b, c from table1 where a="%s"'%var]
    

    【讨论】:

    • 这正是问题所在...谢谢!
    • 酷,很高兴它有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2020-03-18
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多