Java JDBC connection status

前端 未结 6 1274
太阳男子
太阳男子 2020-12-02 19:52

I am (successfully) connecting to a database using the following:

java.sql.Connection connect = DriverManager.getConnection(
  \"jdbc:mysql://localhost/some_         


        
6条回答
  •  感情败类
    2020-12-02 20:39

    If you are using MySQL

    public static boolean isDbConnected() {
        final String CHECK_SQL_QUERY = "SELECT 1";
        boolean isConnected = false;
        try {
            final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
            isConnected = true;
        } catch (SQLException | NullPointerException e) {
            // handle SQL error here!
        }
        return isConnected;
    }
    

    I have not tested with other databases. Hope this is helpful.

提交回复
热议问题