【问题标题】:i tried this sql request on python but is not working我在 python 上尝试了这个 sql 请求,但没有工作
【发布时间】:2017-03-15 17:54:00
【问题描述】:

我的代码有以下部分

 cursor.execute("select titre from article WHERE titre LIKE '%s%%' OR paragraphe LIKE '%s%%' " % (cherche, cherche)  )

如果参数 (cherche) 的值在句子的开头,结果是正确的问题,但我希望所有结果都包含 paranee 和 titre 包含单词 (cherche)。

【问题讨论】:

  • 你还没有真正提供足够的信息,但我要试一试:cursor.execute("select titre from article WHERE titre LIKE '%%%s%%' OR paragraphe LIKE '%%%s%%' " % (cherche, cherche) )

标签: python sql python-2.7 sqlite


【解决方案1】:

cherche 的值被替换后,看看这个字符串是什么样子可能会有所帮助。在cherche 之前不会有%wildcard,这样搜索只会返回cherche 开始 的结果。 Here 是 SQL 通配符入门。

那么我有一些不请自来的建议:不要在 SQL 语句中使用 python 格式!使用execute() built-in substitution否则您遭受SQL injection的痛苦,无论是被一个厚脸皮的用户使用,还是因为您自己意外地提供了一条 SQL 语句。

您的代码采用 sql 清理格式并在结果中的任意位置点击关键字:

sql = "select titre from article WHERE titre LIKE :key OR paragraphe LIKE :key "
cursor.execute(sql, key='%'+cherche+'%' )

请注意,我使用的是sqlalchemy(和oracle_cx)冒号关键字样式的语法。 sqlite3 模块使用问号进行参数替换,不支持关键字样式替换。

【讨论】:

  • 感谢 Sebastian 的帮助,但实际上它不起作用,我尝试使用以下代码并正在工作: cursor.execute("select titre,date_publication from article WHERE titre LIKE ? 或段落 LIKE ?", ('%'+cherche+'%', '%'+cherche+'%',))
  • 这是sqlite3 模块的API 方面。 sqlite3 仅支持 ? 替换 afaik,而例如 sqlalchemy(也兼容 sqlite)将 :key 用于 dict 参数,:1 用于非关键字参数。不过,公平点,我会更新我的答案。
猜你喜欢
  • 2020-11-08
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多