Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC: Find out if query was successful?

Tags:

java

mysql

jdbc

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.

like image 756
user1795609 Avatar asked Dec 16 '22 17:12

user1795609


2 Answers

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

like image 155
a_horse_with_no_name Avatar answered Dec 26 '22 11:12

a_horse_with_no_name


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
}
like image 35
Reimeus Avatar answered Dec 26 '22 11:12

Reimeus