我正在使用 python 從 ORACLE 表中提取資料。我可以使用以下方法拉出其中一個串列所需的行
office_list = [aaa, aab, aac, aad]
&& 實際串列要長得多
"""
SELECT *
FROM (
SELECT distinct(id) as id,
office,
cym,
type
FROM oracle1.table1
WHERE office IN ({0})
)
""".format("'" "','".join([str(i) for i in office_list]) "'")
我無法弄清楚的是如何還包括來自不同串列的另一個過濾器。
在這種情況下,它是一個型別串列
type_list = [type1, type2, type3, type4]
任何幫助,將不勝感激。謝謝
uj5u.com熱心網友回復:
在 cx_oracle 中,將集合傳遞給查詢。使用系結變數將有助于防止 SQL 注入攻擊,并允許 SQL 引擎重用不同串列的執行計劃,這將提供更高的性能(相反,使用字串連接會使您的代碼容易受到 SQL 注入攻擊,并且不允許重新執行計劃的使用)。
在 SQL 中:
CREATE OR REPLACE TYPE string_list AS TABLE OF VARCHAR2(25);
/
在 Python 中:
list_type = connection.gettype("STRING_LIST")
office_list = list_type.newobject()
office_list.extend(["aaa", "aab", "aac", "aad"])
type_list = list_type.newobject()
type_list.extend(["xxx", "xxy", "xxz", "xyz"])
cursor.execute(
"""SELECT DISTINCT
id, -- DISTINCT is NOT a function.
office,
cym,
type
FROM oracle1.table1
WHERE office in (SELECT column_value FROM TABLE(:1))
AND type in (SELECT column_value FROM TABLE(:2))""",
[office_list, type_list],
)
for row in cursor:
print(row)
您可以將WHERE條款簡化為:
WHERE office MEMBER OF TABLE(:1)
AND type MEMBER OF TABLE(:2)
uj5u.com熱心網友回復:
"""select * from(
select
distinct(id) as id,
office,
cym,
type
from oracle1.table1
where office in ({0})
and type in ({1})
)
""".format("'" "','".join(office_list) "'", "'" "','".join(type_list) "'")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353903.html
