【问题标题】:SQLAlchemy(Python): TypeError: can only concatenate tuple (not "RowProxy") to tupleSQLAlchemy(Python):TypeError:只能将元组(不是“RowProxy”)连接到元组
【发布时间】:2021-03-04 08:29:35
【问题描述】:

我正在执行一个将返回单个列的选择查询,并且我正在尝试将返回的 Row 对象转换为元组。但我似乎遇到了错误:

    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 查询的输出并一一附加/打印值,但宁愿使用单行

编辑:

查询select id from some_database.some_table 中的列id 具有字母数字值。所以预期的输出可能是: ('ff123', 'df456', 'gv789')

【问题讨论】:

  • this 会回答您的问题吗? (如果我正确理解您的问题,您希望将元组集合展平为ints 的集合)
  • 嗨,@snakecharmerb,tuple(conn.execute('select id from some_database.some_table') 的输出是 (('123',), ('456',))。我想将其转换为 ('123','456') 而不将其从字符串更改为 int,因为我在以后的 sql 查询中使用这些值。示例:select *** from *** where id in ('123','456')
  • 那么ids = tuple(r for r, in conn.execute(...))?
  • 是的,就像我在问题中提到的那样,我可以使用 for 循环,但我想知道的是,为什么这不起作用 - sum(tuple(conn.execute('select id from some_database.some_table')), ())

标签: python python-3.x sqlalchemy


【解决方案1】:

首先,你有错误的括号位置。

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 转换为元组,将产生 cmets 中提到的结果 - (('123',), ('456',)),因此您最好使用 map 来解压缩值并生成它们平:


value = sum(
    map(
        lambda x: x[0],
        conn.execute(..., ())
    )
)

【讨论】:

  • 嗨@Icebreaker454,您的解决方案sum(tuple(conn.execute('select id from some_database.some_table'), ())) 导致错误:TypeError: tuple() takes at most 1 argument (2 given)
  • 而你提到的lambda解决方案导致错误:TypeError: unsupported operand type(s) for +: 'int' and 'str'这是我尝试的代码:sum(map(lambda x: x[0], conn.execute('select id from some_database.some_table', ())))
  • 我想对于 lambda,您应该尝试将结果设为整数(或您的数据库中的任何数据类型),例如 lambda x: int(x[0])
  • 嗨,请检查编辑,输出列有字母数字值,所以不能选择转换。
  • 你不可能对字符串值求和,所以你必须编写某种过滤函数。例如。有一个值ab123,这个函数可以决定如何从中提取任何数字信息。它将被命名为def predicate(value):,您可以将其代替 lambda 提供给地图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
  • 2022-01-11
相关资源
最近更新 更多