Skip to content
Advertisement

python tuple in sql string

I have a sql query like this:

"...AND A IN (12,13,14)..."

now I want to replace the (12,13,14) with a python tuple that may contain far more than 3 three elements.

In Matlab, I can simply write

'AND A IN',my_tuple, 

How can I achieve the same result in python?

Advertisement

Answer

using f-string for simplicity:

t = ('1','2','3')
sql_string = f"SELECT * FROM FOO WHERE A IN ({','.join(t)})"
print(sql_string) # SELECT * FROM FOO WHERE A IN (1,2,3)

BUT: In case you use any kind of DBAPI use their build in Bind-Parameter logic and avoid concatinating your own SQL-Queries to avoid SQL-Injection etc…

AND: most databases limit the amount of values you can put into an IN(...) clause, for example Oracle only allows 1000 values

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement