简体   繁体   中英

JDBC - reset connection

I am very new to Java.

I have Java class which implements the Database(Postgres) related functionality.

The problem is if Database stopped and then restart then My this class throws SQLException as connection got reset(database is up and running).

Is there any way that after Database restarted; my class automatically Connection to database and work as expected instead of throwing SQLException.

Is there any way with Properties as parameter to DriverManager.getConnection().

Thanks MAP

Use a try catch block to handle the 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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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