I have a list that changes size (and values) depending on the data it gets from a different table. Is there a way to use the list as a variable in place of the = (?)
in the execute function?
I could add the number of (?)
needed using a for loop that would add it to the command
# some function that adds or changes value of var
var = [1, 2, 3]
cmd = """SELECT * FROM table WHERE col IN ("""
for i in range(len(var)):
cmd = """(?)"""
print(cmd, i)
if i < len(var) - 1:
cmd = """, """
print(cmd, i)
if i == len(var) - 1:
cmd = """)"""
print(cmd, i)
c.execute(cmd, (var))
is there a way for me to just input the list as a whole similar to this.
c.execute("""SELECT * FROM table WHERE col IN (?)""",
(var))
This doesn't work due to an error 'Incorrect number of bindings supplied'. Which makes sense.
CodePudding user response:
Maybe something like this could work for you:
# some function that adds or changes value of var
var = [1, 2, 3]
var_to_str = str(var)[1:-1]
cmd = f"SELECT * FROM table WHERE col IN ({var_to_str})"
c.execute(cmd, (var))