Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JDBC connection status

Tags:

java

sql

jdbc

I am (successfully) connecting to a database using the following:

java.sql.Connection connect = DriverManager.getConnection(   "jdbc:mysql://localhost/some_database?user=some_user&password=some_password"); 

What should I be checking to see if the connection is still open and up after some time?
I was hoping for something like connect.isConnected(); available for me to use.

like image 677
MonoThreaded Avatar asked Oct 14 '11 07:10

MonoThreaded


People also ask

How do I know if my JDBC connection is successful?

First, it submits a validation query to the database. Second, it uses the timeout parameter as a threshold for the operation. Finally, the connection is marked as valid if the operation succeeds within the timeout.

What does connection createStatement () do?

createStatement. Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it may be more efficient to use a PreparedStatement object.

How does Spring Boot detect JDBC connection?

To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.


2 Answers

Your best chance is to just perform a simple query against one table, e.g.:

select 1 from SOME_TABLE; 

Oh, I just saw there is a new method available since 1.6:

java.sql.Connection.isValid(int timeoutSeconds):

Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called. The query submitted by the driver to validate the connection shall be executed in the context of the current transaction.

like image 127
home Avatar answered Sep 23 '22 05:09

home


Nothing. Just execute your query. If the connection has died, either your JDBC driver will reconnect (if it supports it, and you enabled it in your connection string--most don't support it) or else you'll get an exception.

If you check the connection is up, it might fall over before you actually execute your query, so you gain absolutely nothing by checking.

That said, a lot of connection pools validate a connection by doing something like SELECT 1 before handing connections out. But this is nothing more than just executing a query, so you might just as well execute your business query.

like image 27
dty Avatar answered Sep 25 '22 05:09

dty