Python CX_Oracle : How to use returned tuples in another query

标签 python cx-oracle

我正在使用 cx_Oracle 通过 Python 查询我的数据库。我有一个返回多个结果的查询。在 cx_Oracle 中,对返回多个结果的查询使用 .fetchall() 命令将每一行放入一个元组中,然后创建一个元组列表(每个返回行 1 个)。 获取查询结果后,其格式如下:

[('R100',), ('R200',)]

我现在想在另一个查询中使用这些结果。下一个查询如下:

base_query = "从 USER.TABLE 中选择 MODEL,其中 :series 中的 SERIES"

其中 :series 是一个特殊的参数标记,当您执行如下查询时可以替换它:

cursor.execute(base_query, series=[('R100',), ('R200',)])

当我尝试将系列设置为元组列表时,出现此错误:

cx_Oracle.NotSupportedError:元素 0 值不受支持

我知道这可能是一个语法问题,因为在原始 SQL 中我试图创建一个如下所示的查询:

base_query = "从 USER.TABLE 中选择 MODEL,其中 SERIES 在 [('R100',), ('R200',)]"

当我真正想要的是这样的时候:

base_query = "从 USER.TABLE 中选择 MODEL,其中 SERIES 在 ('R100','R200')

我在使解析的原始查询看起来像第二个示例时遇到了麻烦,因为我不确定如何解释 python 数据类型(我猜测我的第一个示例甚至不是对原始 SQL 的正确解释)看起来像)

更新: 所以我认为你应该能够通过以下方式来做到这一点: cursor.executemany(base_query, [('R100',), ('R200',)]) 但我收到错误:cx_Oracle.DatabaseError: DPI-1013: not support 我正在使用 cx_oracle Ver 7.0.0 试图找出我的数据库现在是什么版本

最佳答案

您可以使用此函数转换格式,然后在查询中使用它。

    def to_tuple(first_output):
        series = []
        for py_tuple in first_output:
            series.append(py_tuple[0])
        return tuple(series)

    series = to_tuple(first_output) # Output : ('R100', 'R200')
    query = "select MODEL from USER.TABLE where SERIES in {}".format(series) 
    #Output:"select MODEL from USER.TABLE where SERIES in ('R100', 'R200')"

关于Python CX_Oracle : How to use returned tuples in another query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52857858/

相关文章:

python - 数据读取-csv

python - 如何用狮身人面像制作两列

python - 在 Linux 上调用 cx_Oracle 之前设置正确的环境变量

python - 数据库错误: DPI-1047: Cannot locate a 64-bit Oracle Client library (Running cx_Oracle in anaconda python)

python - re.sub python 收集高度

Python检查缓存键是否存在

python - 将 cx_Oracle arraysize 参数与 pandas read_sql 结合使用

python - 接口(interface)错误 : Unable to acquire Oracle environment handle; ORACLE_HOME is correct and SQL*Plus will connect

python - 如何更改outputtypehandler中的datetime.date类型?

python - 无效枚举