Java JDBC Postgresql Driver class and URL example

Here's a quick post to help anyone that needs a quick JDBC Driver and URL reference when using Postgresql (Postgres) with Java (and JDBC).

The basic Postgresql JDBC Driver and URL information you need is shown here:

Postgresql (Postgres) URL (JDBC Connection) String:

Postgresql (Postgres) JDBC Driver String:

It may also help to see this used in a simple Java JDBC application. To that end, here's a simple Java JDBC Postgresql example that shows how to use the Postgres Driver and URL to establish a database connection.

public class JdbcPostgresqlDriverUrlExample
  public static void main(String[] args)
    Connection connection = null;
      // the postgresql driver string
      // the postgresql url
      String url = "jdbc:postgresql://THE_HOST/THE_DATABASE";
      // get the postgresql database connection
      connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
      // now do whatever you want to do with the connection
      // ...
    catch (ClassNotFoundException e)
    catch (SQLException e)

I hope that simple reference helps. There are also many other Java, JDBC, and Postgresql tutorials on this site. Just use our search form to find many other examples.



When I used code - please change following line

connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");

Instead of above line write

Connection connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");


Amit Pandya

Did you use all the code shown in the example? The Connection object reference is declared before the "try" block, and then used inside the block, so it should work fine as is.

In this small example your change makes the code more simple, but in a larger example you may want to close the connection, or return it to a connection pool, and that was part of the reason for me writing it the way I did. I think in my first example I was closing the connection in a "finally" block, but then removed it.

Either way, it should work fine, so thanks for the note.