使用Oracle序列中插入记录ID为从JDBC 2个表?(Using Oracle sequence

2019-09-16 17:16发布

我使用Oracle序列插入记录ID为TABLEA如下,

String SQL_PREP_INSERT = "INSERT INTO tableA (LOG_ID,USER_ID,EXEC_TIME) VALUES"
            + " (logid_seq.nextval, ?, ?)";

然后获取最近插入的值,

String SQL_PREP_SEL = "SELECT max(LOG_ID) FROM tableA ";

stmt = con.prepareStatement(SQL_PREP_SEL);
stmt.execute();
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
logid = rs.getInt(1);
}

并将其插入到tableB的,

String SQL_PREP_INSERT_DETAIL = "INSERT INTO tableB (LOG_ID, RESPONSE_CODE, RESPONSE_MSG) VALUES"
                + " (?, ?)";

        stmt = con.prepareStatement(SQL_PREP_INSERT_DETAIL);
        stmt.setInt(1, logid);
        stmt.setString(2, respCode);
        stmt.setString(3, respMsg);
        stmt.execute();

有没有办法在Java中,而不是甲骨文生成序列,并插入到两个表一次,而不是从TableA的选择并插入到tableB的?

Answer 1:

一般来说,在选择MAX(log_id)是不会给你相同的值logid_seq.nextval提供。 假设这是一个多用户系统,其他一些用户可能已插入了较大的另一行log_id比执行查询之前,您刚插入的行值。

假设两个INSERT语句在同一个会话中运行,最简单的方法可能是使用logid_seq.currval在第二个INSERT语句。 currval将返回返回到当前会话所以它总是返回由生成相同的值序列的最后一个值nextval在第一条语句调用。

INSERT INTO tableB (LOG_ID, RESPONSE_CODE, RESPONSE_MSG) 
  VALUES( logid_seq.currval, ?, ? )

另外,您也可以使用RETURNING子句中的第一个语句序列数值读取到本地变量和使用,在第二个INSERT语句。 但是,这不是简单地使用可能更多的工作currval



Answer 2:

String QUERY = "INSERT INTO students "+
               "  VALUES (student_seq.NEXTVAL,"+
               "         'Harry', 'harry@hogwarts.edu', '31-July-1980')";

// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");

// get database connection from connection string
Connection connection = DriverManager.getConnection(
        "jdbc:oracle:thin:@localhost:1521:sample", "scott", "tiger");

// prepare statement to execute insert query
// note the 2nd argument passed to prepareStatement() method
// pass name of primary key column, in this case student_id is
// generated from sequence
PreparedStatement ps = connection.prepareStatement(QUERY,
        new String[] { "student_id" });

// local variable to hold auto generated student id
Long studentId = null;

// execute the insert statement, if success get the primary key value
if (ps.executeUpdate() > 0) {

    // getGeneratedKeys() returns result set of keys that were auto
    // generated
    // in our case student_id column
    ResultSet generatedKeys = ps.getGeneratedKeys();

    // if resultset has data, get the primary key value
    // of last inserted record
    if (null != generatedKeys && generatedKeys.next()) {

        // voila! we got student id which was generated from sequence
        studentId = generatedKeys.getLong(1);
    }

}


文章来源: Using Oracle sequence to insert log id into 2 tables from jdbc?