Merge pull request #11658 from andresluzu/andres.luzuriaga/BAEL-4498

BAEL-4498 JDBC Connection Status
This commit is contained in:
davidmartinezbarua 2022-02-04 14:05:13 -08:00 committed by GitHub
commit e561a56193
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));
}
}