简体   繁体   English

JDBC-重置连接

[英]JDBC - reset connection

I am very new to Java. 我对Java非常陌生。

I have Java class which implements the Database(Postgres) related functionality. 我有实现数据库(Postgres)相关功能的Java类。

The problem is if Database stopped and then restart then My this class throws SQLException as connection got reset(database is up and running). 问题是,如果数据库已停止然后重新启动,则当连接重置(数据库已启动并正在运行)时,我的此类抛出SQLException。

Is there any way that after Database restarted; 数据库重启后有什么办法吗? my class automatically Connection to database and work as expected instead of throwing SQLException. 我的班级自动连接到数据库并按预期工作,而不是抛出SQLException。

Is there any way with Properties as parameter to DriverManager.getConnection(). 有什么办法可以将Properties作为DriverManager.getConnection()的参数。

Thanks MAP 谢谢MAP

Use a try catch block to handle the SQLException. 使用try catch块来处理SQLException。 When you catch an SQLException, the program could wait a specified period of time and then try to reconnect, you could loop this as long as you want. 当您捕获到SQLException时,程序可以等待指定的时间段,然后尝试重新连接,您可以根据需要进行循环。

boolean connected = false;
// repeat until connected is true
while (!connected) {
    try {
       // put your connection code here
       connected == true;
    } catch (SQLException se) {
       // sleep for 10 seconds
       Thread.sleep(10000);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM