简体   繁体   English

简单的问题。 如何转换python列表以在sqlite查询中成功使用它

[英]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.

相关问题 简单的 python 问题。 如何使我的列表中的值在输入中读取。 我知道这对你们来说可能太基础了,但我需要弄清楚 - Simple python question. How do I make the values in my list read in an input. I know this is prob too basic for u guys but I need to figure this out Python字典问题。 如何对相似的字符串进行分组? - Python dict question. How to group similar strings? 如何在列表中的python中查询SQLite 3 - How to query SQLite 3 in python that is in a list 一般编程问题。 什么时候使用OOP? - General programming question. When to use OOP? Python代码重构问题。 简单化 - Python code refactoring question. Simplification 简单的python列表理解问题 - simple python list comprehension question 我花了 45 分钟来回答这个 python 列表问题。 什么是更简单的方法? - It took me 45 minutes to answer this python list question. What is a simpler method? 会议时间表问题。 如何将此代码转换为MySQL(或任何其他SQL) - Meeting Schedule question. How do I convert this code to MySQL(or any other SQL) 基本时间复杂度问题。 这个简单 function 的时间复杂度 - Basic time complexity question. Time complexity of this simple function 我试图确定一个字符串是否是一个问题。 我如何分析“?”符号(python) - I am trying to determine if a string is a Question. How can I analyze the “?” symbol (python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM