0

I do some insert in a MySQL DB with a for cycle.

I have a problem with the auto-increment, 'cause after the first insert I obtain an com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException.

Here the code:

for (int i=0; i<numKeys; i++) {
try {
   stm1 = this.db_connection.prepareStatement("INSERT INTO mytable (Cod, Prop, Field, Value) VALUES (?,?,?,?)");
   stm1.setInt(1, Statement.RETURN_GENERATED_KEYS);
   stm1.setInt(2, 0);
   stm1.setString(3, aname);  
   stm1.setString(4, avalue);
       stm1.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}  

Cod is an auto-increment-field.

3 Answers 3

2

If it is a auto incremented field then there is no reason to pass it in as an argument, just don't include it in the Insert statement.

stm1 = this.db_connection.prepareStatement("INSERT INTO mytable (Prop, Field, Value) VALUES (?,?,?)");

And remove the appropriate setInt method below.

Sign up to request clarification or add additional context in comments.

Comments

1

Statement.RETURN_GENERATED_KEYS is a int constants,

If you try adding it multiple time with same primary key it will fail to add

1 Comment

Well that and the fact its an auto increment field so he really shouldn't be setting its value himself.
0

If Cod is autoincrement you don't need to insert it. You should try the following code.

for (int i=0; i<numKeys; i++) {
try {
   stm1 = this.db_connection.prepareStatement("INSERT INTO mytable (Prop, Field, Value) VALUES (?,?,?)");
   stm1.setInt(1, 0);
   stm1.setString(2, aname);  
   stm1.setString(3, avalue);
   stm1.executeUpdate();
} catch (SQLException e) {
    e.printStackTrace();
}

}

2 Comments

I don't think this would work, you are passing in a different number of paramaters to values in the sql statement. See my answer below. To clarify, you need to remove one of the ? in the values part of your sql statement so that there are only 3 of them.
@JonTaylor yes my mistake! Thnks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.