Stats

188 Contributors: 1 Wednesday, April 5, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Connect to PostgreSQL from Java

Introduction

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.

Remarks

JDBC URL

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:

jdbc:postgresql://localhost/test?user=fred&password=secret&ssl&sslfactory=org.postgresql.ssl.NonValidatingFactory

References

Related Examples