我正在执行一个选择查询,它将返回一个列,我试图将返回的行对象转换为元组。但我似乎低于错误:
ids = sum(tuple(conn.execute('select id from some_database.some_table')), ())
TypeError: can only concatenate tuple (not "RowProxy") to tuple
示例代码:
with sqlalchemy_engine.connect() as conn:
ids = sum(tuple(conn.execute('select id from some_database.some_table')), ()) # statement causing error
print(ids)
预期输出:('123','456','789')
我可以迭代的输出,选择查询并逐个附加/打印值,但更愿意使用一行
编辑:
查询select id from some_database.some_table
中id
列的值为字母数字。因此预期输出可以是:('ff123', 'df456', 'gv789')
首先,你的括号位置不对。
sum(tuple(conn.execute('select id from some_database.some_table')), ())
应固定为
sum(tuple(conn.execute('select id from some_database.some_table'), ()))
这将使tuple
调用成功。由于您正在调用tuple(conn.execute(...), ())
,它确实试图将conn.execute
和()
的结果连接起来。
注意将您的RowProxy
转换为元组,将产生注释中提到的结果-(('123',), ('456',))
,因此您可以更好地使用map
来解压缩值并使它们平坦:
value = sum(
map(
lambda x: x[0],
conn.execute(..., ())
)
)