newprint
newprint

Reputation: 7100

MySQL and Java - throwing exception when inserting into the table

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?

Upvotes: 0

Views: 2183

Answers (1)

samlewis
samlewis

Reputation: 4048

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.

Upvotes: 1

Related Questions