Python: Create Sql raw query with In clause with list data

一曲冷凌霜 提交于 2021-01-28 10:14:07

问题


Recently I stuck for a moment while preparing the raw Sql Query having In clause to it and the In clause data is a python list. Okay Let me put my example here.

Sql Query that I wanted

sql_query = 'SELECT * FROM student WHERE first_name IN ("Dean");'

From the data I was having

data = ["Dean"]
query = 'SELECT * FROM student WHERE first_name IN %s;' % str(tuple(data))
# result was "SELECT * FROM student WHERE first_name IN ('Dean',) "
# see the *Comma* just before close parentheses which is a Sql error

But After doing some practice I came up with a solution of something like this

str_data = ','.join(repr(x) for x in data)
query = 'SELECT * FROM student WHERE first_name IN (%s);' % str_data

# Gives proper result i.e "SELECT * FROM student WHERE first_name IN ('Dean');"

Now my question is, is this a elegant solution or we have several other optimized approaches out there in python. Would be appreciable to have your views on this :).

Edit Reached to another solution

data = tuple(data) if len(data) > 1 else "('%s')" % data[0] # Assumption: data  should not be empty (in my case it is true)
query = 'SELECT * FROM student WHERE first_name IN {};'.format(data)

Note: Still looking for some views from you guys if it can be optimized further.


回答1:


I used this in python3 on a postgres database, specifically if you want strings after the IN operator. please pay attention to the double quotes vs single quotes:

data = ['test', 'test2', 'test3']
data_str = "', '".join(data)
query = "SELECT * FROM student WHERE first_name IN ('{}');".format(data_str))

or like this if you prefer f-strings:

print(f"SELECT * FROM student WHERE first_name IN ('{data_str}');")


来源:https://stackoverflow.com/questions/29443867/python-create-sql-raw-query-with-in-clause-with-list-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!