Insert using PreparedStatement. How do I auto-increment the ID?

前端 未结 3 747
悲哀的现实
悲哀的现实 2020-12-05 18:39

I have a PreparedStatement such as:

 PreparedStatement preparedStatement = connect.prepareStatement(\"INSERT into employee (id, time, name\" + \"(?,?,?)\",St         


        
3条回答
  •  不思量自难忘°
    2020-12-05 19:17

    Leave the column out of the INSERT statement entirely. It will be generated by the database engine. Your query should be:

    INSERT INTO employee (time, name)
    VALUES (?, ?)
    

    Secondly, you have to perform the insert first, then get the keys out of the result.

    I believe your code should be:

    PreparedStatement preparedStatement = 
        connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)", 
        Statement.RETURN_GENERATED_KEYS);
    
    preparedStatement.setTimestamp(1, 
        new java.sql.Timestamp(new java.util.Date().getTime()));                           
    preparedStatement.setString(2, "Test");
    
    preparedStatement.executeUpdate();
    
    ResultSet tableKeys = preparedStatement.getGeneratedKeys();
    tableKeys.next();
    int autoGeneratedID = tableKeys.getInt(1);
    

    Note this example does not check the success of the executed statement or the existence of returned keys.

提交回复
热议问题