我生成了一个 ID 号列表。我想执行一个插入语句,从一个表中获取 ID 值在我的列表中的所有记录,并将这些记录插入到另一个表中。
我发现了这个 cx_Oracle 函数,而不是运行多个执行语句(据我所知是可能的),它可以用单个语句和列表参数执行所有内容。(它还避免了在传入参数之前对 SQL 语句进行笨重的格式设置)但我认为我需要在将其作为参数传入之前更改我的列表。只是不确定如何。
我参考了这个网页:https : //dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html
ids = getIDs()
print(ids)
[('12345',),('24567',),('78945',),('65423',)]
sql = """insert into scheme.newtable
select id, data1, data2, data3
from scheme.oldtable
where id in (%s)"""
cursor.prepare(sql)
cursor.executemany(None, ids)
我希望 SQL 语句执行如下:
插入scheme.newtable select id, data1, data2, data3 from scheme.oldtable where id in ('12345','24567','78945','65423')
相反,我收到以下错误:ORA-01036:非法变量名称/编号
编辑:我发现了这个 StackOverflow:如何使用 Python 批量插入 Oracle 数据库?我更新了我的代码以事先准备好语句并将列表项更新为元组,但我仍然遇到相同的错误。
您executemany()
用于批处理 DML,例如,当您想将大量值插入表中作为运行多个插入语句的有效等效项时。在https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle 中讨论了 cx_Oracle 示例
但是你在做什么
insert into scheme.newtable
select id, data1, data2, data3
from scheme.oldtable
where id in (%s)
是另一回事 - 您正在尝试使用 IN 子句中的多个值执行一个 INSERT 语句。您将为此使用法线execute()
。
由于 Oracle 保持与 SQL 不同的绑定数据,您不能将多个值传递给单个绑定参数,因为数据被视为单个 SQL 实体,而不是值列表。您可以使用%s
现有的字符串替换语法,但这对 SQL 注入攻击是开放的。
Oracle 语言接口有多种通用技术,请参阅https://oracle.github.io/node-oracledb/doc/api.html#sqlwherein,了解可以重写为 Python 语法的解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句