插入后的Java JDBC检索ID [英] Java JDBC Retrieve ID After Insert

查看:155
本文介绍了插入后的Java JDBC检索ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用触发器来设置所有表的PK列值,所以我不对Java中的ID做任何操作,但我需要插入后的ID。

I use triggers to set PK column values of all tables so i do not do any operation about IDs in java but i need the ID after insert.

我如何获得身份证?

stat.execute("INSERT INTO TPROJECT_PROCESS_GROUP(NPROJECT_ID,VDESCRIPTION) " +
                "VALUES(" +
                "'" + projectID + "'," +
                "'" + description + "'" +
                "");

编辑:嗨再次我读了这个问题,现在我得到一个例外,例如'不支持的操作'(我翻译自我的母语,确切的英文形式可能会有所不同)。猜猜这是关于oracle对GetGeneratedKeys的支持吗?你对此有何了解?

Hi again I read the question, now I get an exception like 'unsupported operation'(i translated from my native language the exact english form might be different). i guess this is about oracle's support for GetGeneratedKeys? Do you know anything about this?

解决方案:正如关于callablestatements的书中所提到的这句话可以用来执行存储过程和与PreparedStatement不同,大多数数据库都不对调用执行任何准备,因为它是一个如此简单的命令.CallableStatement实例可用于返回存储过程或函数的对象,更准确地返回。 / p>

Solution: As mentioned in a book about callablestatements This statement can be used to execute stored procedures and functions. Unlike the PreparedStatement, most databases do not perform any preparation for the call,because it is such a simple command. The CallableStatement instances can be used toreturn the object that the stored procedure—or function, to be more exact—returned.

OracleConnection conn = null;
    //OraclePreparedStatement pstat = null;
    OracleCallableStatement cstat = null;
    String sql = "BEGIN INSERT INTO TPROJECT P (VPROJECT_TITLE,VPROJECT_DESC)    VALUES(?,?) RETURNING P.NPROJECT_ID INTO ?;  END;";
    try {
        conn = ConnectionUtility.GetConnection();
        cstat = (OracleCallableStatement)conn.prepareCall(sql);

        cstat.setString(1, title);
        cstat.setString(2, description);
        cstat.registerOutParameter(3, OracleTypes.NUMBER);
        cstat.execute();

        int returnedID = cstat.getInt(3);
//          System.out.println(returnedID);

        conn.close();

        return returnedID;


推荐答案

这个例子就是你在PostgreSQL中的表现。希望你能在Oracle中做类似的事情。

This example is how you would do it in PostgreSQL. Hopefully you can do something similar in Oracle.

这是你在 INSERT INTO 之后获取自动生成的密钥的方式,如串行。这里重要的是在prepareStatement()调用中提供 RETURN_GENERATED_KEYS

This is how you get the id after INSERT INTO for auto-generated keys like serial . Important here is to provide RETURN_GENERATED_KEYS in the prepareStatement() call.

Resultset result;
PreparedStatement prep;
String query = "INSERT INTO myRel (data) VALUES (?)";

prep = db.prepareStatement(query ,Statement.RETURN_GENERATED_KEYS);

result = prep.getGeneratedKeys();

if(result.next() && result != null){
   System.out.println("Key: " + result.getInt(1));
} else {
   System.out.println("No, Nop nada");
}

希望能帮到某人:)

这篇关于插入后的Java JDBC检索ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆