我正在为基于 Django 的应用程序编写一个 python 模块,该应用程序通过 cx_Oracle 访问 Oracle 数据库。“似乎”django 代码有一个错误,它破坏了 cx_Oracle “executemany”方法的使用。如果我使用 cx_Oracle 并严格通过 cx_Oracle 打开连接,则逻辑工作正常。通过 django 使用连接,它失败了。
由于 django 是一项要求,我正在寻找一种解决方法,并且需要了解它失败的语句(如下)试图做什么。我知道“%”既用作模运算符又用作字符串格式,因为在这种情况下显然是这样。但是,尽管进行了很多搜索,但这似乎不符合我能找到的使用“%”的任何字符串格式语法。有人可以解释这是要做什么吗?
query = query % tuple(args)
TypeError: not all arguments converted during string formatting
在哪里:
query = 'INSERT INTO DATABASE.TABLE\n (DATE, ID, COL_A, COL_B, COL_C)\n VALUES (:1, :2, :3, :4, :5)\n'
args = [':arg0', ':arg1', ':arg2', ':arg3', ':arg4']
如果你在 REPL 中输入这些值和上面的语句,你会得到同样的错误。
我知道我应该提交一份 django 错误报告。稍后会弄清楚。现在我希望我能以某种方式更改查询字符串中的 Oracle 绑定变量位置表示法以满足上述语句。同样,查询字符串直接与 cx_Oracle 一起工作没有问题。
细节:
Python 3.6.5 :: Anaconda, Inc.
CX-Oracle 7.0.0
Django 2.0.7
cx_Oracle 查询格式: https ://www.oracle.com/technetwork/articles/dsl/prez-python-queries-101587.html (见“Many at Once”)
我的 cx_Oracle 代码:
cursor = conn.cursor()
cursor.prepare(query)
cursor.executemany(query, list_of_tuples_of_values)
rows_affected = cursor.rowcount
conn.commit()
失败的代码在 django 模块 base.py 中,第 494 行: (C:\python\Anaconda2\envs\py36\lib\site-packages\django\db\backends\oracle\base.py)
def _fix_for_params(self, query, params, unify_by_values=False):
# cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it
# it does want a trailing ';' but not a trailing '/'. However, these
# characters must be included in the original query in case the query
# is being passed to SQL*Plus.
if query.endswith(';') or query.endswith('/'):
query = query[:-1]
if params is None:
params = []
elif hasattr(params, 'keys'):
# Handle params as dict
args = {k: ":%s" % k for k in params}
query = query % args
elif unify_by_values and len(params) > 0:
# Handle params as a dict with unified query parameters by their
# values. It can be used only in single query execute() because
# executemany() shares the formatted query with each of the params
# list. e.g. for input params = [0.75, 2, 0.75, 'sth', 0.75]
# params_dict = {0.75: ':arg0', 2: ':arg1', 'sth': ':arg2'}
# args = [':arg0', ':arg1', ':arg0', ':arg2', ':arg0']
# params = {':arg0': 0.75, ':arg1': 2, ':arg2': 'sth'}
params_dict = {param: ':arg%d' % i for i, param in enumerate(set(params))}
args = [params_dict[param] for param in params]
params = {value: key for key, value in params_dict.items()}
query = query % tuple(args)
else:
# Handle params as sequence
args = [(':arg%d' % i) for i in range(len(params))]
query = query % tuple(args) <==============
return query, self._format_params(params)
params = (datetime.datetime(2018, 10, 12, 0, 0), '123456', 10, 10, 8)