简体   繁体   English

使用Python变量搜索SQLite3数据库

[英]Search SQLite3 database using a Python variable

I am trying to search my SQLite3 database using a pythonic variable as a search term. 我正在尝试使用pythonic变量作为搜索词来搜索我的SQLite3数据库。 The term I'm searching for is a part of the contents of the cell in the database (eg Smith in a cell: [Harrison GB, Smith JH]) and is often in the middle of the string in a cell. 我要搜索的术语是数据库中单元格内容的一部分(例如,单元格中的Smith:[Harrison GB, Smith JH]),并且通常位于单元格中字符串的中间。

I have tried to code it as shown below: 我尝试将其编码如下所示:

def read_from_db():
    c.execute("SELECT authors, year, title, abstract FROM usertable WHERE authors LIKE (?)",(var1,))
    data = c.fetchall()
    print(data)
    for row in data:
        searchlist.append(row)

var1="Smith"
read_from_db()

This should show the results row after row. 这应该逐行显示结果。 However, I get 0 results when var1 = " Smith ". 但是,当var1 =“ Smith ”时,我得到0个结果。 When I change its value to " Harrison GB, Smith JH ", I get all the results. 当我将其值更改为“ Harrison GB,Smith JH ”时, 我得到了所有结果。

When I try to solve it by changing the SQLite3 execute query I yield an error. 当我尝试通过更改SQLite3执行查询来解决它时,出现错误。

ERROR
    c.execute("SELECT authors, year, title, abstract FROM usertable WHERE authors LIKE '%?%'",(var1,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.

I get syntax errors if I change the endings with: $?$, (%?%) etc. I tried this with: 如果将结尾更改为$?$,(%?%)等,则会出现语法错误。

...authors="%?%"

But this doesn't work either. 但这也不起作用。 There is a few similar questions on SO, but they don't exactly solve my issue... SO上也有一些类似的问题,但它们并不能完全解决我的问题...

I am running Python 3.4 and SQLite3 on Windows 10. 我在Windows 10上运行Python 3.4和SQLite3。

Consider concatenating the % wildcards to the binded value, var1 : 考虑将%通配符连接到绑定值var1

c.execute("SELECT authors, year, title, abstract" +
          " FROM usertable WHERE authors LIKE (?)", ('%'+var1+'%',))

The reason you need to do so is the ? 您需要这样做的原因是? placeholder substitutes a string literal in parameterized queries and for LIKE expressions, wildcards with values together are string literals as denoted by their enclosed single quotes: 占位符在参数化查询中替换字符串文字,对于LIKE表达式,带有值的通配符一起是字符串文字,如用其单引号引起来:

SELECT authors, year, title, abstract FROM usertable WHERE authors LIKE '%Smith%'

Your initial attempt failed because you wrap ? 您最初的尝试失败了,因为您换行了? with single quotes and the cursor cannot bind the param to prepared statement properly and so the symbol is taken literally as question mark. 用单引号引起来,并且光标无法将参数正确绑定到准备好的语句,因此该符号从字面上被视为问号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM