[英]Simple Question. How to convert python list to successfully use it in sqlite query
I am trying to put test1 list into db query where :count is.我正在尝试将 test1 列表放入 :count 所在的数据库查询中。 Problem is it should be working fine as if I were to put WHERE id in (1, 2), but using my code it is not.
问题是它应该可以正常工作,就像我将 WHERE id 放在 (1, 2) 中一样,但使用我的代码却不是。 Fix needed, will appreciate any teaching.
需要修复,将欣赏任何教学。 I am new to programming.
我是编程新手。
from cs50 import SQL
db = SQL("sqlite:///database.db")
test2 = [1, 2]
test3 = str(test2).strip('[]')
print(test3)
dbcounted = db.execute('SELECT * FROM products WHERE id in (:count);', count = test3)
print(dbcounted)
Going off the CS50 documentation it looks like it expects an array instead of a string.从CS50 文档来看,它看起来需要一个数组而不是一个字符串。 So this gives you two options:
所以这给了你两个选择:
Assemble a full string and pass it:组装一个完整的字符串并传递它:
from cs50 import SQL
db = SQL("sqlite:///database.db")
test2 = [1, 2]
ex_str = 'SELECT * FROM products WHERE id in (' + str(test2).strip('[]') + ');'
print(ex_str)
dbcounted = db.execute(ex_str)
print(dbcounted)
Or you can pass count as an array as expected by the function call:或者您可以按照函数调用的预期将 count 作为数组传递:
from cs50 import SQL
db = SQL("sqlite:///database.db")
test2 = [1, 2]
dbcounted = db.execute('SELECT * FROM products WHERE id in (:count);', count = test2)
print(dbcounted)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.