使用JDBC重新连接

Man*_*noj 2 java jdbc

我正在使用JDBC连接到数据库.由于网络速度很慢,我可以在手动重试2或3次后获得连接.如果连接失败,是否可以自动重试连接?我正在使用SQLServer 2008数据库.谢谢

Bal*_*usC 9

已经可以配置一个像样的连接池,例如BoneCP.大多数人甚至默认这样做.如果你不使用连接池而只是基本的DriverManager#getConnection()方法,那么你必须自己在while循环中重新执行它,只要它Connectionnull.

这是一个基本的启动示例:

Connection connection = null;

while (connection == null) {
    try {
        connection = DriverManager.getConnection(url, username, password);
    } catch (SQLException e) {
        logger.info("Connecting failed, retrying...");
    }
}

return connection;
Run Code Online (Sandbox Code Playgroud)

当然,这可以通过中间的较长暂停和设置最大重试次数等来进行更优化.