Python, SQLAlchemy在connection.execute中传递参数。

9 浏览
0 Comments

Python, SQLAlchemy在connection.execute中传递参数。

我正在使用SQLAlchemy的connection.execute(sql)将查询结果转换为一个由映射组成的数组。以下是我的代码:

def __sql_to_data(sql):

result = []

connection = engine.connect()

try:

rows = connection.execute(sql)

for row in rows:

result_row = {}

for col in row.keys():

result_row[str(col)] = str(row[col])

result.append(result_row)

finally:

connection.close()

return result

例如,__sql_to_data(sql_get_scan_candidate)给我一个很好的数据结构(当然,我只用于小数据集)。

但是为了给sql添加参数,我目前是使用format函数,例如:return __sql_to_data(sql_get_profile.format(user_id))。

问题是如何修改这个过程以实现类似这样的效果:return __sql_to_data(sql_get_profile,user_id)。

0