0

I am new MySQL user trying to write program that manipulates database through Java.

Have table named users with the following attributes | USERNAME | EMAIL | ROLE |, where USERNAME is PRIMARY KEY and rest of the attributes are NOT NULL.

Lets say I do INSERT INTO users, since there is Primary Key constrain on USERNAME MySQL should throw error. How this error will be throw and how do I catch it within JAVA ? Do I need to write Stored procedure for throwing errors or INSERT INTO statement has this capability as well?

2
  • Why don't you first try to follow one of many tutorials on this topic and ask a question when you encounter a specific problem you can't solve? As a hint, I would use a PreparedStatement instead of a Statement. Commented Mar 26, 2013 at 19:54
  • 2
    I Googled mysql insert from java and on the first page of results I found a good prepared statement example here. Downside: its exception handling is terrible. The first hit with decent exception handling is here. Between the two you'll figure it out. Finally, MySQL will throw when appropriate; you don't have to do anything special. Commented Mar 26, 2013 at 20:12

1 Answer 1

1

If the primary key is violated an SQLException will be thrown with a message containing the name of the constraint that was violated. Your exception handling can look something like this:

try {
    //do the insert
} catch (SQLException e) {
    if(e.getMessage().contains("MY_CONSTRAINT_NAME")) {
        //duplicate key
    } else {
        //some other error
    }
}

An alternative is to check SQLException.getSQLState() or SQLException.getErrorCode().

I would recommend using Spring JDBC which takes care of SQLException translation and generally reduces the amount of JDBC codeyou need to write.

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

Comments

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.