2

我正在使用 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 而不是 Oracle 中生成序列并一次插入两个表中,而不是从 tableA 中选择并插入到 tableB 中?

4

2 回答 2

7

通常,选择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.

于 2012-04-23T17:09:20.167 回答
0
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);
    }

}
于 2014-11-06T17:14:37.030 回答