How to get the insert ID in JDBC?

后端 未结 12 1756
暖寄归人
暖寄归人 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条回答
  •  眼角桃花
    2020-11-21 06:34

    Instead of a comment, I just want to answer post.


    Interface java.sql.PreparedStatement

    1. columnIndexes « You can use prepareStatement function that accepts columnIndexes and SQL statement. Where columnIndexes allowed constant flags are Statement.RETURN_GENERATED_KEYS1 or Statement.NO_GENERATED_KEYS[2], SQL statement that may contain one or more '?' IN parameter placeholders.

      SYNTAX «

      Connection.prepareStatement(String sql, int autoGeneratedKeys)
      Connection.prepareStatement(String sql, int[] columnIndexes)
      

      Example:

      PreparedStatement pstmt = 
          conn.prepareStatement( insertSQL, Statement.RETURN_GENERATED_KEYS );
      

    1. columnNames « List out the columnNames like 'id', 'uniqueID', .... in the target table that contain the auto-generated keys that should be returned. The driver will ignore them if the SQL statement is not an INSERT statement.

      SYNTAX «

      Connection.prepareStatement(String sql, String[] columnNames)
      

      Example:

      String columnNames[] = new String[] { "id" };
      PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
      

    Full Example:

    public static void insertAutoIncrement_SQL(String UserName, String Language, String Message) {
        String DB_URL = "jdbc:mysql://localhost:3306/test", DB_User = "root", DB_Password = "";
    
        String insertSQL = "INSERT INTO `unicodeinfo`( `UserName`, `Language`, `Message`) VALUES (?,?,?)";
                //"INSERT INTO `unicodeinfo`(`id`, `UserName`, `Language`, `Message`) VALUES (?,?,?,?)";
        int primkey = 0 ;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection(DB_URL, DB_User, DB_Password);
    
            String columnNames[] = new String[] { "id" };
    
            PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
            pstmt.setString(1, UserName );
            pstmt.setString(2, Language );
            pstmt.setString(3, Message );
    
            if (pstmt.executeUpdate() > 0) {
                // Retrieves any auto-generated keys created as a result of executing this Statement object
                java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
                if ( generatedKeys.next() ) {
                    primkey = generatedKeys.getInt(1);
                }
            }
            System.out.println("Record updated with id = "+primkey);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题