rag*_*rdl 6 python oracle oracle12c
我想回到我(通过python中的cx_oracle)为我正在插入的行创建的Identity的值.我想我可以自己找出python位,如果有人可以请说明如何修改我的SQL语句以获取新创建的行的ID.
我有一个用以下内容创建的表:
CREATE TABLE hypervisor
(
id NUMBER GENERATED BY DEFAULT AS IDENTITY (
START WITH 1 NOCACHE ORDER ) NOT NULL ,
name VARCHAR2 (50)
)
LOGGING ;
ALTER TABLE hypervisor ADD CONSTRAINT hypervisor_PK PRIMARY KEY ( id ) ;
Run Code Online (Sandbox Code Playgroud)
我有类似于以下内容的SQL:
insert into hypervisor ( name ) values ('my hypervisor')
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法来获得id新插入的行?如果可能的话,我很乐意修改我的SQL语句以使其返回.
关于此问题的大多数谷歌点击是针对版本11及更低版本,它不支持自动生成的标识列,所以希望有人可以提供帮助.
拿用user2502422上面说的并添加python位:
newest_id_wrapper = cursor.var(cx_Oracle.STRING)
sql_params = { "newest_id_sql_param" : newest_id_wrapper }
sql = "insert into hypervisor ( name ) values ('my hypervisor') " + \
"returning id into :python_var"
cursor.execute(sql, sql_params)
newest_id=newest_id_wrapper.getvalue()
Run Code Online (Sandbox Code Playgroud)
这个来自learncodeshare.net 的例子帮助我掌握了正确的语法。
cur = con.cursor()
new_id = cur.var(cx_Oracle.NUMBER)
statement = 'insert into cx_people(name, age, notes) values (:1, :2, :3) returning id into :4'
cur.execute(statement, ('Sandy', 31, 'I like horses', new_id))
sandy_id = new_id.getvalue()
pet_statement = 'insert into cx_pets (name, owner, type) values (:1, :2, :3)'
cur.execute(pet_statement, ('Big Red', sandy_id, 'horse'))
con.commit()
Run Code Online (Sandbox Code Playgroud)
它与 ragerdl 的答案仅略有不同,但我相信可以在此处添加不同的内容!注意没有sql_params = { "newest_id_sql_param" : newest_id_wrapper }
| 归档时间: |
|
| 查看次数: |
2065 次 |
| 最近记录: |