Open dev112233 opened 5 years ago
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@Component
public class ConnectionChecker {
public boolean isConnectionValid(DataSource dataSource) {
try (Connection connection = dataSource.getConnection()) {
return connection.isValid(3); // Adjust timeout as needed
} catch (SQLException e) {
return false;
}
}
public static void main(String[] args) {
// Example usage
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydatabase");
config.setUsername("username");
config.setPassword("password");
DataSource dataSource = new HikariDataSource(config);
ConnectionChecker checker = new ConnectionChecker();
System.out.println("Is connection valid? " + checker.isConnectionValid(dataSource));
}
}
Environment
Hi, This is not an issue, but a question that I wanted to ask about a functionality. I have asked the question in stackoverflow @https://stackoverflow.com/questions/55258128/connection-checker-java-class-in-spring-boot-using-hikaricp
Could you please suggest a way of achieving what I have asked in the question ?
Thanks