3

I wanna ask about how to get message response from PostgreSQL when we execute a query.

Message response from PostgreSQL what I mean are like this, for example:

  • Query returned successfully: 1 row affected, 11 ms execution time.
  • ERROR: duplicate key value violates unique constraint "pk_grouptab"
  • etc.

I am using JDBC.

I have tried to get it from executeUpdate() from Statement class. but it's only return int that representing whether the query executed successfully or not.

Is there any way to do it?

1 Answer 1

3

I am not sure whether you get statements like

Query returned successfully: 1 row affected, 11 ms execution time.

but you have alternative to use like statement.executeUpdate() which returns the the no of rows that have been affected by the execution of the DML statement.

Coming to the other statement

ERROR: duplicate key value violates unique constraint "pk_grouptab"

Whenever an error has occurred in the database, a SQLException is thrown, you need to explicitly catch the exception and handle it. SQLException Api in addition, please check this link where it briefly describes exception handling in JDBC.

If you want to check if there were any warnings after you execute a query you can use getWarnings and use methods like getMessage() to get the message of the warning.

Below is a skeleton

 try {
     // execute sql statements here
     log.info(statement.getWarnings().getMessage());
 }
 catch(SQLException ex) {
     // an exception has occurred get all info related to the exception
     log.info(ex.getErrorCode());
     log.info(ex.getMessage());
     ex.printStackTrace();
 }
 finally {
     // close all open connections
 }

Hope this helps you.

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

3 Comments

Thank a lot, Patton. I'll use SQLExcetion for any error message response in my app and executeUpdate() to get the number of rows that have been affected by the execution.
You are welcome! If you come across any issues just let me know!
@ilyasfals: It is suggested to accpe the helpful answer.

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.