ProgramingTip

준비된 명령문에서 자동 증가 ID를 검색하는 방법이 있습니까?

bestdevel 2020. 12. 8. 19:22
반응형

준비된 명령문에서 자동 증가 ID를 검색하는 방법이 있습니까?


준비된 문장으로 자바 쿼리를 사용할 때 DB 쿼리에서 자동 된 생성 키를 검색하는 방법이 있습니까?

예를 들어 AutoGeneratedKeys가 다음과 같이 작동 할 수 있는지 알고 있습니다.

stmt = conn.createStatement();

stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
    ResultSet rs = stmt.getGeneratedKeys();
    rs.next();
    auto_id = rs.getInt(1);
} 

하나. 지불 준비된 성명서로 지불해야합니까?

String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);

//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
    //this is an error since the above is an error
    ResultSet rs = stmt.getGeneratedKeys();
    rs.next();
    auto_id = rs.getInt(1);
} 

내가 알지 못하시는 방법이 있습니까? Javadoc에서 PreparedStatements가 자동 생성 ID를 반환 할 수 있습니다.


예. 를 참조하십시오 여기 . 7.1.9 항. 코드를 다음과 같이 변경하십시오.

String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);


stmt.executeUpdate();
if(returnLastInsertId) {
   ResultSet rs = stmt.getGeneratedKeys();
    rs.next();
   auto_id = rs.getInt(1);
}

몇 가지 방법이 있고 다른 jdbc 드라이버가 약간 다른 것을 처리하거나 일부 경우에는 전혀 처리하지 않는 것입니다 (일부는 자동으로 처리하지 않는 것). 기본 형식은 다음과 가변합니다.

stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); 

또는 다음 양식을 사용하십시오.

String autogenColumns[] = {"column1","column2"};
stmt = conn.prepareStatement(sql, autogenColumns)


예, 방법이 있습니다. 방금 Java 문서에 숨어있는 것을 발견했습니다.

다음과 같이 AutoGeneratedKeys ID를 전달하는 것입니다.

String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

저는이 문제에 대한 해결책을 찾기 위해 몇 개의 단일성을 검색 한 사람 중 한 명입니다. 그리고 마침내 작동하게됩니다. jdbc : oracle : thin : ojdbc6.jar 사용 참고 : 두 가지 방법 중 하나를 사용할 수 있습니다. (방법 1)

Try{
    String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
    myPrepStatement = <Connection>.prepareStatement(yourSQL, Statement.RETURN_GENERATED_KEYS);
    myPrepStatement.setInt(1, 123); 
    myPrepStatement.setInt(2, 123); 

    myPrepStatement.executeUpdate();
    ResultSet rs = getGeneratedKeys;
    if(rs.next()) {
      java.sql.RowId rid=rs.getRowId(1); 
      //what you get is only a RowId ref, try make use of it anyway U could think of
      System.out.println(rid);
    }
} catch (SQLException e) {
  //
}

(방법 2)

Try{
    String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
    //IMPORTANT: here's where other threads don tell U, you need to list ALL cols 
    //mentioned in your query in the array
    myPrepStatement = <Connection>.prepareStatement(yourSQL, new String[]{"Id","Col2","Col3"});
    myPrepStatement.setInt(1, 123); 
    myPrepStatement.setInt(2, 123); 
    myPrepStatement.executeUpdate();
    ResultSet rs = getGeneratedKeys;
    if(rs.next()) {
    //In this exp, the autoKey val is in 1st col
    int id=rs.getLong(1);
    //now this's a real value of col Id
    System.out.println(id);
    }
} catch (SQLException e) {
  //
}

Method1을 사용하지 않고 기본적으로 SEQ.Nextval의 값을 원합니다. 그냥 사용하려고 머리를 깨 뜨렸을 수있는 RowID 참조를 반환합니다. 또한 캐스팅을 시도한 모든 데이터 유형에 맞지 않습니다. 그것! 이것은 MySQL, DB2에서는 잘 작동하지만 (실제 값 반환) Oracle에서는 작동하지 않을 수 있습니다.

그리고 디버깅 할 때 SQL Developer, Toad 또는 동일한 로그인 세션을 사용하여 INSERT를 수행하는 모든 클라이언트를 끕니다. (디버깅 호출) 매번 영향을 미치지 않을 수도 있습니다. 앱이 한동안 예외없이 정지 될 때까지. 예 ... 예외없이 중지하십시오!


    Connection connection=null;
    int generatedkey=0;
    PreparedStatement pstmt=connection.prepareStatement("Your insert query");
    ResultSet rs=pstmt.getGeneratedKeys();
    if (rs.next()) {
       generatedkey=rs.getInt(1);   
               System.out.println("Auto Generated Primary Key " + generatedkey); 
    }

참고 URL : https://stackoverflow.com/questions/1376218/is-there-a-way-to-retrieve-the-autoincrement-id-from-a-prepared-statement

반응형