【问题标题】:OperationalError: near "%": syntax error with sqlite3 in PythonOperationalError:“%”附近:Python 中 sqlite3 的语法错误
【发布时间】:2019-07-09 02:42:25
【问题描述】:

我在 Python 中使用 sqlite3 包并尝试从名为 orders 的表中选择单个条目。我想获取列 order_date 的值以 18 结尾的条目(这是一个 varchar 列,该条目的实际值为“10/20/2018”)。

根据类似问题的指导,我构建了如下查询:

sql = """SELECT * FROM orders
            WHERE order_date LIKE %s"""

args = ['%' + '18']

c.execute(sql, args)

但我得到了这个:

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-51-e6a345ebe6eb> in <module>
      6 args = ['%' + '18']
      7 
----> 8 c.execute(sql, args)
      9 conn.commit()
     10 

OperationalError: near "%": syntax error

我尝试了多种方式来构建查询,但每次都得到相同的错误。根据我浏览过的其他问题,这应该可行。怎么了?

【问题讨论】:

    标签: python sql sqlite syntax operationalerror


    【解决方案1】:

    您应该使用?作为绑定变量的占位符,而不是%s

    sql = """SELECT * FROM orders
                WHERE order_date LIKE ?"""
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多