简体   繁体   English

Python中的SQLite3 WHERE子句

[英]SQLite3 WHERE Clause In Python

Just recently ran into a problem running python 3.3 using SQLite3. 就在最近,使用SQLite3运行python 3.3时遇到了问题。 I've created a fairly large table so I'll just use a small example: 我创建了一个相当大的表,所以我只使用一个小例子:

CREATE TABLE X(omega TEXT, z TEXT, id INT);

Now, I'm using various functions to access this table from a main script. 现在,我正在使用各种功能从主脚本访问该表。 In one of the functions I have the code: 在其中一个功能中,我有以下代码:

cur.execute("SELECT omega,z FROM X WHERE omega=?",Omega)

This works just fine when I have the Omega variable set as a one-character string. 当我将Omega变量设置为一个字符的字符串时,这很好用。 However, when I increase the number of characters (ex. if Omega='10'), then I get the following error: 但是,当我增加字符数(例如,如果Omega = '10')时,会出现以下错误:

    cur.execute("SELECT omega,z FROM X WHERE omega=?",Omega)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.

Now, I HAVE found a workaround: 现在,我找到了一种解决方法:

cur.execute("SELECT omega,z FROM X WHERE omega="+Omega)

but I'd like to know why this works and the "proper" method of using a question mark doesn't. 但是我想知道为什么会这样,而使用问号的“正确”方法却行不通。

Thanks in advance! 提前致谢!

cur.execute("SELECT omega,z FROM X WHERE omega=?",(Omega,))

since a string is iterable it tries to bind each letter to a ? 由于字符串是可迭代的,因此它尝试将每个字母绑定到?。 (eg it sees cur.execute("SELECT omega,z FROM X WHERE omega=?",('1','0')) instead of cur.execute("SELECT omega,z FROM X WHERE omega=?",('10',)) (例如,它看到cur.execute("SELECT omega,z FROM X WHERE omega=?",('1','0'))而不是cur.execute("SELECT omega,z FROM X WHERE omega=?",('10',))

if you specify like this it knows the string is one item that binds to the question mark 如果您这样指定,它将知道字符串是绑定到问号的一项

According to this documentation , the second parameter to execute() should be a tuple. 根据本文档execute()的第二个参数应该是一个元组。 Presumably the bindings are using duck-typing, and since a string acts like a tuple, it gets treated like one. 大概绑定使用的是鸭式输入,并且由于字符串的作用类似于元组,因此将其视为一个。 You can fix this by changing the second parameter to a tuple: 您可以通过将第二个参数更改为元组来解决此问题:

cur.execute("SELECT omega,z FROM X WHERE omega=?", (Omega,))

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

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