如何在“:songs”中传递列表?
如果我传递一个key:value对,那么原始SQL将起作用,但是当我尝试传递一个列表时,它将不起作用。我收到AttributeError:列表对象没有属性“键”。
songs = ('Song1', 'Song2', 'Song3', 'Song4', 'Song5')
engine = app.db.engine
connection = engine.connect()
rawSqlResult = text(
"SELECT * FROM AlbumView WHERE Song IN :songs")
queryResult = connection.execute(rawSqlResult, songs)
tempDict, resultList = {}, []
for rowproxy in queryResult:
for tup in rowproxy.items():
tempDict = {**tempDict, **{tup[0]: tup[1]}}
resultList.append(tempDict)
print(resultList)
答案 0 :(得分:0)
This approach解决了我的问题:
my_list = ['peach', 'grape', 'apple']
query_parameters = {}
counter = 1
for list_item in my_list:
query_parameters["list_item" + str(counter)] = list_item
counter += 1
where_clause = 'fruits IN(:' + ",:".join(query_parameters.keys()) + ')' # create clause to be inserted into query
query_text = db.text("""
SELECT fruits
FROM table
WHERE """ + where_clause + """ """)
result = db.engine.execute(query_text, **query_parameters)