How to get the insert ID in JDBC?

后端 未结 12 1757
暖寄归人
暖寄归人 2020-11-21 06:09

I want to INSERT a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can

12条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 06:25

    1. Create Generated Column

      String generatedColumns[] = { "ID" };
      
    2. Pass this geneated Column to your statement

      PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
      
    3. Use ResultSet object to fetch the GeneratedKeys on Statement

      ResultSet rs = stmtInsert.getGeneratedKeys();
      
      if (rs.next()) {
          long id = rs.getLong(1);
          System.out.println("Inserted ID -" + id); // display inserted record
      }
      

提交回复
热议问题