user1795609
user1795609

Reputation: 157

JDBC: Find out if query was successful?

I'm using JDBC with mysql. I can get my queries to work great. But for update queries for instance I was wondering if there was any way to determine whether the update was successful for for example if the row could not be found.

UPDATE TABLE SET  column =  'newvalue' WHERE  primary_key =2

I would like to get the specific error message if possible, this way I can throw a specific exception as to why the query failed.

Thanks for your help.

Upvotes: 6

Views: 22467

Answers (2)

Reimeus
Reimeus

Reputation: 159754

executeUpdate returns the row count of rows affected. You could use this to check that your update was executed successfully:

PreparedStatement pstmt = con.prepareStatement("UPDATE TABLE ...");
int rowsUpdated = pstmt.executeUpdate(); 
if (rowsUpdated == 0) {
   // handle no update
}

Upvotes: 3

user330315
user330315

Reputation:

executeUpdate() will return the number of rows that were affected by your SQL statement:

int rows = stmt.executeUpdate("UPDATE ...");
System.out.println(rows + " rows updated");

Of course you could have found out yourself by simply looking at the JavaDocs:

Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

Upvotes: 11

Related Questions