Home > Back-end >  Trouble connecting to postgresql via JDBC
Trouble connecting to postgresql via JDBC

Time:08-01

I am trying to connect to the postgressql server hosted in the same computer from JDBC, but can see nothing printed on the console, not even the exception. Here is the code for the same

import java.util.Scanner;    
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;

public class Driver {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Connection c = null;
        try {
            System.out.println("Before connection");  //This is getting printed
            c = DriverManager.getConnection("jdbc:postgresql://localhost:53574/","postgres","**");
            System.out.println("After connection");  //This is not getting printed
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

After entering the correct password, phrase Before connection is getting printed while After connection is not getting printed. I tried changing the port number and only then the exception Connection to localhost:5357 refused is caught.

Please help me figure out the mistake I'm doing. Thank you in advance.

CodePudding user response:

I think you can check whether your port number is wrong(default port number is 5432 not 5357) or you can use netstat -ntlp to check what port is open on your computer.

CodePudding user response:

Reasons

  • Driver is not available.
  • Nothing is listening on the Port you are
  • Postgresql isn't running.
  • Postgresql isn't listening for TCP/IP connections.
  • Postgresql is listening on a different port to the one you're connecting on.

When the Postgresql server daemon is not running in the server, it can trigger connection refused error. At the same time, several other reasons can also trigger this error.

When you are scanning ports 1 to 65535, this is expected to happen with most ports. It's a sign that you should move on to the next port.

Solution

Download Latest PostgreSQL JDBC Driver

To connect to the PostgreSQL database server from a Java program, you need to have PostgreSQL JDBC driver. You can download the latest version of the driver on the postgresql.org website via the download page. The downloaded file is a jar file. You should copy it to a specific folder e.g. C:\demo\libs so that you can remember its location and be able to add it to your Java application later.

Then , add the PostgreSQL JDBC driver jar file to the project.

To import jar file in your Eclipse IDE, follow the steps given below.

  1. List item
  2. Right click on your project
  3. Select Build Path
  4. Click on Configure Build Path
  5. Click on Libraries and select Add External JARs
  6. Select the jar file from the required folder
  7. Click and Apply and Ok

then, you need to prepare the following:

  1. The address of the PostgreSQL database server
  2. The database name
  3. The username and password of the account that you will use to connect to the database.

For this information, you can construct the PostgreSQL JDBC connection string by using the following format:

To make it easier, we can define the attributes of the App class for storing connection string, user, and password:

private final String url = "jdbc:postgresql://localhost:5432/databasename";
private final String user = "yourname";
private final String password = "yourpassword";

Code should look like this

MainClass.java

package com.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MainClass {

private final String url = "jdbc:postgresql://localhost:5432/databasename";
private final String user = "yourname";
private final String password = "yourpassword";

public Connection connect() {
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(url, user, password);
        System.out.println("Connected to the PostgreSQL server successfully.");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    return conn;
}

public static void main(String[] args) {
    App app = new App();
    app.connect();
}

}

Run a port scan

make sure the port is opened. To show all connections

Open cmd and enter following command and hit enter

netstat -a

You will see all the active connections from different states as shown below.

You need to edit postgresql.conf (inside your data directory) to set the new port there, then restart the postgresql service using the Services control panel or (as an Administrator) the net service command.

Edit postgresql.conf

This file is usually located in /var/lib/pgsql/data/ on Linux or C:\PostgreSQL\data\ on Windows or similar. In this file we will edit the "listen_address" and "port" parameters, so that they look like below:

Connection Settings

listen_addresses = '0.0.0.0'        # what IP address(es) to listen on;
                    # comma-separated list of addresses;
                    # defaults to 'localhost'; use '*' for all
                    # (change requires restart)
port = 5432             # (change requires restart)

Steps:

  1. Go to..\postgresql\9.0\data and open the file postgresql.conf in text editor/notepad
  2. Search for port parameter .eg: port = 5433
  3. Edit this to your port number.
  4. Go to run type services.msc and restart postgresql service.

Restart PostgreSQL

After that we need to restart PostgreSQL to activate the changes.

On Windows you can use Control Panel -> Administrative Tools -> Services and find service named postgres then restart the PostgreSQL service by right click -> properties - >stop then start.

  • Related