JDBC: find out if the request was successful?

I am using JDBC with mysql. I can make my queries work fine. But for update requests, for example, I was wondering if there was a way to determine if the update was successful, for example, if the row was not found.

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

I would like to receive a specific error message, if possible, this way I can indicate a specific exception, why the request failed.

Thank you for your help.

+4
source share
2 answers

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

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

Of course, you could recognize yourself simply by looking at JavaDocs :

Returns: either (1) the number of rows for SQL Data Manipulation Language (DML) statements, or (2) 0 for SQL statements that return nothing

+10
source

executeUpdate returns the number of lines of the affected lines. You can use this to verify that your update was successful:

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

Source: https://habr.com/ru/post/1446689/


All Articles