postgresql Connect to PostgreSQL from Java

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any postgresql Question?