1

Is it possible to find whether PostgreSQL server is running or not, through java code ? I dint find any relevant solution in net. Any suggestions are really appreciated. Thanks in advance.

2
  • Define running. Is it enough for you to test whether the PostgreSQL port is available on a certain host? Is it enough to check for some postmaster presence on the local machine? Commented Oct 26, 2012 at 12:44
  • 1
    yes that is fine. Finding whether the post is available on the specified host. Commented Oct 26, 2012 at 13:02

2 Answers 2

4

Little bit funny but it will work, here username ,password and url must be correct if server is not running you will get Failed to make connection Check output console

  try {
        Class.forName("org.postgresql.Driver");

        Connection connection = DriverManager.getConnection(
                    "jdbc:postgresql://127.0.0.1:5432/testdb", "username",
                    "password");

          if (connection != null) {
                System.out.println("You made it, take control your database now!");
            } else {
                System.out.println("Failed to make connection!");

        }


    } catch (Exception e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;

    }
Sign up to request clarification or add additional context in comments.

Comments

0

If it's enough for you to check for HOST+PORT availability of your PostgreSQL server, you can do:

public static boolean psqlAvailable(String host, int port) {
    boolean ret = false;
    try {
        Socket s = new Socket(host, port);
        ret = true;
        s.close();
    } catch (Exception e) {
        // 
    }
    return ret;
}

It might be slow, though. To use it:

// assuming these are IP+PORT configuration on your PostgreSQL server.
boolean psql = psqlAvailable("192.168.16.1", 5432);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.