python - 带有 like from 变量的 SQL 语句

标签 python sqlite

我正在用 python 执行这段代码

from sqlite3 import dbapi2 as sqlite

con = sqlite.connect("db.sqlite")
cur = con.cursor()
surname = "'%atton%'"
cur.execute("select id from singers where surname like :surname", locals())
cur.close()
con.close()

在这段代码之后 cur.rowcount == -1 但 Patton 在数据库中。

我的 SQL 语句有问题吗?

谢谢

最佳答案

您使用的 DB-API 参数化(您应该使用,不要更改它)意味着姓氏将被自动引用或适本地转义。您应该从 surname 字符串中删除内部引号集。

surname = "%atton%"
cur.execute("select id from singers where surname like :surname",
    dict(surname=surname))

关于python - 带有 like from 变量的 SQL 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6123590/

相关文章:

python - 在存在条件的数据库中查找非唯一值

javascript - pdf生成后重定向

python - 在 Python 中读取文件时忽略空行的最简单方法

python - python 中的 3D 绘图,x 刻度和标签之间的空间

python - 错误 : sqlite3. 操作错误 : no such table: main. m

node.js - 使用 Webpack 捆绑 Sqlite3 导致编译错误

python - 遍历目录

python - 使用 Python 和 elasticsearch,如何遍历返回的 JSON 对象?

iphone - 将部分 mySQL DB 从网站转换为 iOS 上的 CoreData/SQLite

python - 'str' 对象没有属性 'execute'