Python cx_oracle 绑定变量与项目列表

Python cx_oracle bind variable with a list of items

我有这样的查询:

SELECT prodId, prod_name , prod_type FROM mytable WHERE prod_type in (:list_prod_names)

我想获取一个产品的信息,取决于可能的类型有:"day", "week", "weekend", "month"。根据日期,它可能至少是这些选项中的一个,或者是所有选项的组合。

此信息(列表类型)由函数prod_names(date_search)

返回

我正在使用 cx_oracle 绑定,代码如下:

def get_prod_by_type(search_date :datetime):

  query_path = r'./queries/prod_by_name.sql'
  raw_query = open(query_path).read().strip().replace('\n', ' ').replace('\t', ' ').replace('  ', ' ')

  print(sql_read_op)
  # Depending on the date the product types may be different
  prod_names(search_date)  #This returns a list with possible names
  qry_params = {"list_prod_names": prod_names} # See attempts bellow
  try:
      db = DB(username='username', password='pss', hostname="localhost")
      df = db.get(raw_query,qry_params)
  except Exception:
      exception_error = traceback.format_exc()
      exception_error = 'Exception on DB.get_short_cov_op2() : %s\n%s' % exception_error
      print(exception_error)
  return df

为此:qry_params = {"list_prod_names": prod_names} 我尝试了多种不同的方法,例如:

prod_names = ''.join(prod_names) 
prod_names = str(prod_names)
prod_names =." \'"+''.join(prod_names)+"\'"

我唯一让它工作的方法是:

new_query = raw_query.format(list_prod_names=prodnames_for_date(search_date)).replace('[', '').replace(']','')

df = db.query(new_query)

我尽量不使用 .format(),因为将 .format 转换为 sql 以防止攻击是不好的做法。

db.py 包含其他功能:

def get(self, sql, params={}):
cur = self.con.cursor()
            cur.prepare(sql)
            try:
                cur.execute(sql, **params)
                df = pd.DataFrame(cur.fetchall(), columns=[c[0] for c in cur.description])
            except Exception:
                exception_error = traceback.format_exc()
                exception_error = 'Exception on DB.get() : %s\n%s' % exception_error
                print(exception_error)
                self.con.rollback()
            cur.close()
            df.columns = df.columns.map(lambda x: x.upper())
         return df

我希望能够进行类型绑定。

我正在使用:

我已经阅读了以下文章,但仍然无法找到解决方案:

不幸的是,您不能直接绑定数组,除非您将其转换为 SQL 类型并使用子查询——这相当复杂。所以你需要做这样的事情:

inClauseParts = []
for i, inValue in enumerate(ARRAY_VALUE):
    argName = "arg_" + str(i + 1)
    inClauseParts.append(":" + argName)
clause = "%s in (%s)" % (columnName, ",".join(inClauseParts))

这很好用,但请注意,如果数组中的元素数量有规律地变化,那么使用此技术将创建一个单独的语句,必须针对每个元素数量进行解析。如果您知道(通常)数组中的元素不会超过(例如)10 个,最好将 None 附加到传入数组,以便元素数始终为 10。

希望已经足够清楚了!

我终于做到了。它可能不漂亮,但它确实有效。

我已经修改了我的 sql 查询以包含一个额外的 select,其中 returns 我的描述符列表的值:

inner join (
   SELECT regexp_substr(:my_list_of_items, '[^,]+', 1, LEVEL) as mylist
   FROM dual
   CONNECT BY LEVEL <= length(:my_list_of_items) - length(REPLACE(:my_list_of_items, ',', '')) + 1
) d
on d.mylist= a.corresponding_columns