python - 插入并返回 :array
问题描述
我想在 oracle 中的表中添加多行并将添加的值返回到 python 列表
返回的列是主键,在oracle端生成
我写的代码不起作用,这是可以理解的,但是我不知道该怎么写。请帮帮我
out_id = cursor.var(cx_Oracle.NUMBER)
batch = []
for i in range(3):
batch.append({'val': i})
ins = 'INSERT INTO table (col1) VALUES (:val) RETURNING table.col2 into :out_id'
cursor.executemany(ins, batch)
print(list_out_id.getvalue())
我收到一个错误
ORA-01036: 非法变量名称/编号
解决方案
For printing output in the format
[{'val': 1, 'out_id': id_1}, {'val': 2, 'out_id': id_2}, {...}]
the following code will work
import cx_Oracle
# Establish the database connection - Add your DB details here
connection = cx_Oracle.connect(
user="hr", password="hr", dsn="localhost/orclpdb")
# Obtain a cursor cursor = connection.cursor()
# set the input and output variables
out_id = cursor.var(int, arraysize=3)
batch = []
for i in range(3):
batch.append({'val': i, 'out_id': out_id})
# set the SQL statement
ins = 'INSERT INTO table(col1) VALUES (:val) RETURNING table.col2 into :out_id'
# run the query and fetch the output into 'out_id' variable
cursor.executemany(ins, batch)
#print the output in the required format
for i in range(3):
batch[i]['out_id'] = batch[i]['out_id'].getvalue(i)
print(batch)
print(out_id.values)
# Do a commit to the table if required
# connection.commit()
推荐阅读
- swift - NSKeyedArchiver:转换数据返回 nil - Swift
- latex - 删除乳胶流程图中最后一个单元格到第一个单元格的箭头
- python-3.x - 将 pickle 文件从协议 3 转换为协议 2
- javascript - sourceOne.peek 不是函数
- android - 为什么imageView在android中会翻倍?
- c# - 但问题我有他们想要 20,35,45 是第 15 步,然后是 10
- php - PHP exec()命令不返回Ajax成功函数
- javascript - 有没有办法在 Javascript 中添加链接(包含 php)?
- python - 第一个路由过滤器后的路由
- c++ - 在 C++ 类中实现 TPCircularBuffer