Reputation: 36422
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.
Upvotes: 1
Views: 1946
Reputation: 181290
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);
Upvotes: 0
Reputation: 10953
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;
}
Upvotes: 4