简体   繁体   中英

Check if SQL server is online, using Java

Him using jdbc to connect a simple Java app to a SQL server. It's working perfectly. I want to add an extra to the application, I want to notify the user if the database is reachable our not, by changing the color of a label. Right now I'm using the function:

 private static Connection getDBConnection() {

    Connection dbConnection = null;

    try {

        Class.forName(DB_DRIVER);

    } catch (ClassNotFoundException e) {

        System.out.println(e.getMessage());

    }

    try {

        dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
                DB_PASSWORD);
                    System.out.println("Connection Good");
        return dbConnection;

    } catch (SQLException e) {

        System.out.println(e.getMessage());
                    System.out.println("Connection BAD");

    }

    return dbConnection;

}

I'm not sure if it's the best way to do it. I have to verify if the connection is successful and close the connection right after. If I have an exception verifying the connection our closing the connection my Thread dies...

Is there a best way to verify if the database is reachable? Any suggestions ? Thanks

I would add a dummy query to be completely sure. It would not be the first time a connection seems to be open being the server unreachable:

try {

       dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
                DB_PASSWORD);
                    System.out.println("Connection Good");
       try(Statenent st = dbConnection.createStatement();)
       {
          try(ResultSet res = st.executeQuery("SELECT 1 AS C"))
          {
              if(res.getInt("C") != 1)
                  throw  new SQLException();
          }
       }
    } catch (SQLException e) {

        System.out.println(e.getMessage());
                    System.out.println("Connection BAD");

    }

    return dbConnection;

}

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