programing

PLSQL JDBC:마지막 행 ID를 가져오는 방법?

css3 2023. 6. 19. 21:58

PLSQL JDBC:마지막 행 ID를 가져오는 방법?

이 SQL 서버 스니펫에 해당하는 PLSQL(Oracle)은 무엇입니까?

BEGIN TRAN
INSERT INTO mytable(content) VALUES ("test") -- assume there's an ID column that is autoincrement
SELECT @@IDENTITY
COMMIT TRAN

C#에서 내 명령을 호출할 수 있습니다.Scalar()를 실행하여 새 행의 ID를 검색합니다.

Oracle에서 새 행을 삽입하고 JDBC가 새 ID의 복사본을 가져오도록 하려면 어떻게 해야 합니까?

편집: BalusC는 매우 좋은 출발점을 제공했습니다.어떤 이유에서인지 JDBC는 명명된 매개 변수 바인딩을 좋아하지 않습니다.이렇게 하면 "잘못 설정되거나 등록된 매개 변수" SQL 예외가 표시됩니다.왜 이런 일이 생기는 건가요?

        OracleConnection conn = getAppConnection();
        String q = "BEGIN INSERT INTO tb (id) values (claim_seq.nextval) returning id into :newId; end;" ;
        CallableStatement cs = (OracleCallableStatement) conn.prepareCall(q);
        cs.registerOutParameter("newId", OracleTypes.NUMBER);
        cs.execute();
        int newId = cs.getInt("newId");

일반적으로 이 작업에 사용할 수 있지만(를 들어 이 답변 참조) Oracle JDBC 드라이버는 이 작업을 지원하지 않습니다.

당신의 최선의 방법은 사용하는 입니다.RETURNING절:

String sql = "BEGIN INSERT INTO mytable(id, content) VALUES (seq_mytable.NEXTVAL(), ?) RETURNING id INTO ?; END;";

Connection connection = null;
CallableStatement statement = null;

try {
    connection = database.getConnection();
    statement = connection.prepareCall(sql);
    statement.setString(1, "test");
    statement.registerOutParameter(2, Types.NUMERIC);
    statement.execute();
    int id = statement.getInt(2);
    // ...

아니면SELECT sequencename.CURRVAL끝나고INSERT동일한 트랜잭션에서:

String sql_insert = "INSERT INTO mytable(content) VALUES (?)";
String sql_currval = "SELECT seq_mytable.CURRVAL FROM dual";

Connection connection = null;
PreparedStatement statement = null;
Statement currvalStatement = null;
ResultSet currvalResultSet = null;

try {
    connection = database.getConnection();
    connection.setAutoCommit(false);
    statement = connection.prepareStatement(sql_insert);
    statement.setString(1, "test");
    statement.executeUpdate();
    currvalStatement = connection.createStatement();
    currvalResultSet = currvalStatement.executeQuery(sql_currval);
    if (currvalResultSet.next()) {
        int id = currvalResultSet.getInt(1);
    }
    connection.commit();
    // ...

오라클의 반환 조항을 사용할 수 있습니다.

insert into mytable(content) values ('test') returning your_id into :var;

코드 샘플을 보려면링크를 확인하십시오.Oracle 10g 이상 및 새로운 버전의 JDBC 드라이버가 필요합니다.

키 필드를 명시적으로 선택하여 getGeneratedKeys()를 사용할 수 있습니다.다음은 스니펫입니다.

    // change the string to your connection string
    Connection connection = DriverManager.getConnection("connection string");

    // assume that the field "id" is PK, and PK-trigger exists 
    String sql = "insert into my_table(id) values (default)";
    // you can select key field by field index
    int[] colIdxes = { 1 };
    // or by field name
    String[] colNames = { "id" };

    // Java 1.7 syntax; try-finally for older versions
    try (PreparedStatement preparedStatement = connection.prepareStatement(sql, colNames))
    {
        // note: oracle JDBC driver do not support auto-generated key feature with batch update
        //          // insert 5 rows
        //          for (int i = 0; i < 5; i++)
        //          {
        //              preparedStatement.addBatch();
        //          }
        //          
        //          int[] batch = preparedStatement.executeBatch();
        preparedStatement.executeUpdate();

        // get generated keys
        try (ResultSet resultSet = preparedStatement.getGeneratedKeys())
        {
            while (resultSet.next())
            {
                // assume that the key's type is BIGINT
                long id = resultSet.getLong(1);
                assertTrue(id != 0);

                System.out.println(id);
            }
        }
    }

자세한 내용은 http://docs.oracle.com/cd/E16655_01/java.121/e17657/jdbcvers.htm#CHDEGDHJ 을 참조하십시오.

사용하는 경우spring-jdbc데이터베이스의 경우 더 많은 jdbc의 깔끔한 래퍼를 고려할 수 있으며 다음과 같이 나타납니다.

import static org.morejdbc.SqlTypes.BIGINT;
import static org.morejdbc.JdbcCall.callSql;
import static org.morejdbc.*;
...

Out<Long> idOut = Out.of(BIGINT);
jdbcTemplate.execute(callSql("BEGIN INSERT INTO mytable(id, content) VALUES (seq_mytable.NEXTVAL(), ?) "
        + "RETURNING id INTO ?; END;")
        .in(content)
        .out(BIGINT, idOut));
System.out.println("Id is " + idOut.get());

만약 당신이 pojo 같은 것을 가지고 있다면.

@lombok.Data
public class Entity {
    private long id;
    private String content;
}

그것은 훨씬 더 라코닉할 수 있습니다.

Entity entity = ;

jdbcTemplate.execute(callSql("BEGIN INSERT INTO mytable(id, content) VALUES (seq_mytable.NEXTVAL(), ?) "
        + "RETURNING id INTO ?; END;")
        .in(entity.getContent())
        .out(BIGINT, entity::setId));
System.out.println("Id is " + entity.get());

언급URL : https://stackoverflow.com/questions/3552260/plsql-jdbc-how-to-get-last-row-id