Search code examples
javapostgresqlintellij-idea

IntelliJ - Problem connecting to PostgreSQL


I am new to PostgreSQL (I normally use other database engines), and I also do not use Java often.

My Problem is that I get the following exception:

java.sql.SQLException: No suitable driver found for DATABASE_NAME
 java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
    at
 java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)

I followed this tutorial: http://www.postgresqltutorial.com/postgresql-jdbc/connecting-to-postgresql-database/ and added postgresql-42.2.5.jar as a library.

enter image description here

The problem is that adding the driver as a library, as can be seen in the screenshot, has no effect.

So my question is: how do I connect to a PostgreSQL database using Java and the latest IntelliJ?

Any help would be appreciated.

UPDATE 1: enter image description here

UPDATE 2: Since the code has been requested: I have replaced the original code by a minimal code that will cause the error:

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

public class IngestData
{
    protected static String url;
    protected static final String user = "user";
    protected static final String password = "password";

    public static void main(String[] args)
    {
        Connection connection = null;
        url = args[args.length-1];
        try
        {
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("SUCCESS");

        } catch (SQLException e)
        {
            System.out.println("ERROR");
            e.printStackTrace();
        }
    }
}

The console output is:

ERROR
java.sql.SQLException: No suitable driver found for http://127.0.0.1:10282/db01617792
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
    at IngestData.main(IngestData.java:17)

Process finished with exit code 0

Here is the link to the git repository containing the code: https://github.com/ka6555/StackOverflow-Postgresql-Problem.git

UPDATE 3: I found the error:

I need to change

protected static String url;

to

protected static String url = "jdbc:postgresql://";

and

url = args[args.length-1];

to

url += args[args.length-1];

While this solves my original problem, the program is now stuck executing the following line:

connection = DriverManager.getConnection(url, user, password);

There is no error but the program will simply run like with an endless loop never going beyond this code line.

UPDATE 4: I have fixed all problems now.


Solution

  • The main problem was that I used a command line parameter as the database url without prefixing it with jdbc:postgresql://. Additionally, I had to reinstall postgresql because of some odd behavior I could not figure out the reason for.