douling1936 2015-12-15 09:10
浏览 171

获取最后插入的ID(GO + oracle)

I need to insert two records in Oracle database from my go application using sqlx (https://github.com/jmoiron/sqlx) with go-oci8 (https://github.com/mattn/go-oci8) driver. Second record references previous one by foreign key. So I need to have primary key of first record (it is assigned from sequence with before insert trigger on first table) before I can insert second record.

So I experimented to get last inserted id:

create table t(x int primary key);
create sequence x_seq;

LastInsertId failed for me:

import(
    "fmt"
    "github.com/jmoiron/sqlx"
    _ "github.com/mattn/go-oci8"
)

func main(){
    db, err := sqlx.Connect("oci8", "integr/integr@localhost:49161/xe")
    if err != nil {
       fmt.Println(err)
    }
    sql := "insert into t values(x_seq.nextval)"
    r, err := db.Exec(sql)
    if err != nil {
       fmt.Println(err)
    }
    fmt.Println(r.RowsAffected())
    fmt.Println(r.LastInsertId())
}

Output:

1 <nil>
0 LastInsertId not supported

Then I tried to make stored function that inserts record and returns primary key.

create function f(x int) return int as
v int;
begin
    insert into t values(x)
    returning x into v;
    return v;
end;

But I failed to find a way to get its result. PostgreSQL style select fails:

SQL> select f(9) from dual;
select f(9) from dual
       *
ERROR at line 1:
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "INTEGR.F", line 1

And OCI8 style variable binding does not work:

package main

import(
    "fmt"
    "github.com/jmoiron/sqlx"
    _ "github.com/mattn/go-oci8"
)

func main(){
    db, err := sqlx.Connect("oci8", "integr/integr@localhost:49161/xe")
    if err != nil {
       fmt.Println(err)
    }
    sql := sqlx.Rebind(sqlx.NAMED,"begin ? := f(?); end;")
    var a int
    _, err = db.Exec(sql, a, 333)
    if err != nil {
       fmt.Println(err)
    }
    fmt.Println(sql)
    fmt.Println(a)
}

Output:

begin :arg1 := f(:arg2); end;
0

How to get last inserted ID, or how to get value from stored funcion in Go from Oracle?

  • 写回答

1条回答 默认 最新

  • dongruo0909 2015-12-28 13:31
    关注

    Hi I Don't know about go but I know about oracle return query

    Same problem I had with PHP and I solve it using this query

    insert into table (field1,field2,field3)
    values (val1,val2,val3) return primaryfield_id into :xx
    

    It will automatically return value in your Go variable (I guess ) please try this

    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)