BAEL-4498 JDBC Connection Status

This commit is contained in:
Andres Luzuriaga 2022-01-07 23:56:49 -05:00
parent 143346a850
commit b15df89834
2 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,65 @@
package com.baeldung.connectionstatus;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionValidation
{
public static Connection getConnection()
throws Exception
{
Class.forName("org.h2.Driver");
String url = "jdbc:h2:mem:testdb";
return DriverManager.getConnection(url, "user", "password");
}
public static void runIfOpened(Connection connection)
throws SQLException
{
if (connection != null && !connection.isClosed()) {
// run sql statements
}
else {
// handle closed connection
}
}
public static void runIfValid(Connection connection)
throws SQLException
{
// Try to validate connection with a 5 seconds timeout
if (connection.isValid(5)) {
// run sql statements
}
else {
// handle invalid connection
}
}
public static void runIfConnectionValid(Connection connection)
{
if (isConnectionValid(connection)) {
// run sql statements
}
else {
// handle invalid connection
}
}
public static boolean isConnectionValid(Connection connection)
{
try {
if (connection != null && !connection.isClosed()) {
// Running a simple validation query
connection.prepareStatement("SELECT 1");
return true;
}
}
catch (SQLException e) {
// log some useful data here
}
return false;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.connectionstatus;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ConnectionValidationUnitTest
{
@Test
void givenConnectionObject_whenCreated_thenIsNotClosed()
throws Exception
{
Connection connection = ConnectionValidation.getConnection();
assertNotNull(connection);
assertFalse(connection.isClosed());
}
@Test
void givenConnectionObject_whenCreated_thenIsValid()
throws Exception
{
Connection connection = ConnectionValidation.getConnection();
assertTrue(connection.isValid(0));
}
@Test
void givenConnectionObject_whenValidated_thenIsValid()
throws Exception
{
Connection connection = ConnectionValidation.getConnection();
assertTrue(ConnectionValidation.isConnectionValid(connection));
}
}