简体   繁体   English

使用Python在SQLite中进行变量替换

[英]Variable Substitution in SQLite using Python

I am trying to figure out how to combine two SQLite queries. 我试图弄清楚如何结合两个SQLite查询。 Both of them work fine independently but when I put them together with AND they do not work. 他们两个都可以独立正常工作,但是当我将它们与AND放在一起时AND它们将无法工作。 I think the problem is that I do not know how to pass the variables properly. 我认为问题是我不知道如何正确传递变量。 First query that works: 第一个有效的查询:

var1 = 10
mylist = ['A', 'B', 'C', 'AB', 'AC']
c.execute("SELECT * FROM my_table WHERE column1=(?) ORDER BY RANDOM() LIMIT 1", (mylist[2],))

This line also works: 此行也适用:

params = [5,0,1]
query = ("SELECT * FROM my_table WHERE column2 NOT IN (%s)" % ','.join('?' * len(params)))
c.execute(query, params)

I have been trying to combine these two statements without success: 我一直试图将这两个语句结合在一起而没有成功:

query = ("SELECT * FROM my_table WHERE column2 NOT IN (%s) AND column1=(?)" % ','.join('?' * len(params)))
c.execute(query, params, mylist[2])

In case anyone finds this helpful, my final solution looked like this: 万一有人发现这有帮助,我的最终解决方案如下所示:

query = ("SELECT * FROM my_table WHERE column1 = (?) AND column2 NOT IN (%s) ORDER BY RANDOM() LIMIT 1" % ','.join('?' * len(params)))
    c.execute(query, [mylist[2]] + params)

The second parameter of execute() must be a sequence containing all the SQL parameters. execute()的第二个参数必须是包含所有SQL参数的序列。

So you have to construct a single list with the values from both original lists: 因此,您必须使用两个原始列表中的值构造一个列表:

c.execute(query, params + [list[2]])

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

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