brettwooldridge / HikariCP

光 HikariCP・A solid, high-performance, JDBC connection pool at last.
Apache License 2.0
20.06k stars 2.95k forks source link

A query about HikarCP regarding hikari.connection-test-query #1346

Open dev112233 opened 5 years ago

dev112233 commented 5 years ago

Environment

HikariCP version: 3.2.0
JDK version     : 11
Database        : Oracle 12c
Driver version  : ojdbc7

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

ljluestc commented 6 months 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));
    }
}