postgresqlConnect to PostgreSQL from Java


The API to use a relational database from Java is JDBC.

This API is implemented by a JDBC driver.

To use it, put the JAR-file with the driver on the JAVA class path.

This documentation shows samples how to use the JDBC driver to connect to a database.



The JDBC URL can take one of these forms:

  • jdbc:postgresql://host[:port]/[database][parameters]

    host defaults to localhost, port to 5432.
    If host is an IPv6 address, it must be enclosed in square brackets.
    The default database name is the same as the name of the connecting user.

    To implement failover, it is possible to have several host[:port] entries separated by a comma.
    They are tried in turn until a connection succeeds.

  • jdbc:postgresql:database[parameters]

  • jdbc:postgresql:/[parameters]

    These forms are for connections to localhost.

parameters is a list of key[=value] pairs, headed by ? and separated by &. If the value is missing, it is assumed to be true.

An example: