Initializing the Driver | pgJDBC (original) (raw)

This section describes how to load and initialize the JDBC driver in your programs.

Importing JDBC

Any source file that uses JDBC needs to import the java.sql package, using:

NOTE

You should not import the org.postgresql package unless you are using PostgreSQL® extensions to the JDBC API.

Loading the Driver

Applications do not need to explicitly load the org.postgresql.Driver class because the pgJDBC driver jar supports the Java Service Provider mechanism. The driver will be loaded by the JVM when the application connects to PostgreSQL® (as long as the driver’s jar file is on the classpath).

NOTE

Prior to Java 1.6, the driver had to be loaded by the application: either by calling Class.forName("org.postgresql.Driver"); or by passing the driver class name as a JVM parameter java -Djdbc.drivers=org.postgresql.Driver example.ImageViewer

These older methods of loading the driver are still supported, but they are no longer necessary.

Connecting to the Database

With JDBC, a database is represented by a URL (Uniform Resource Locator). With PostgreSQL®, this takes one of the following forms:

The parameters have the following meanings:

To connect, you need to get a Connection instance from JDBC. To do this, you use the DriverManager.getConnection() method:Connection db = DriverManager.getConnection(url, username, password)

Important

Any reserved characters for URLs (for example, /, :, @, (, ), [, ], &, #, =, ?, and space) that appear in any part of the connection URL must be percent encoded. See RFC 3986 for details.

System Properties

pgjdbc.config.cleanup.thread.ttl (milliseconds, default: 30000). The driver has an internal cleanup thread which monitors and cleans up unclosed connections. This property sets the duration the cleanup thread will keep running if there is nothing to clean up.

Connection Parameters

In addition to the standard connection parameters the driver supports a number of additional properties which can be used to specify additional driver behaviour specific to PostgreSQL®. These properties may be specified in either the connection URL or an additional Properties object parameter to DriverManager.getConnection . The following examples illustrate the use of both methods to establish an SSL connection.

If a property is specified both in URL and in Properties object, the value from Properties object is ignored.

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user", "fred");
props.setProperty("password", "secret");
props.setProperty("ssl", "true");
Connection conn = DriverManager.getConnection(url, props);

String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
Connection conn = DriverManager.getConnection(url);

The value of this property may contain spaces or other special characters, and it should be properly encoded if provided in the connection URL. Spaces are considered to separate command-line arguments, unless escaped with a backslash ( \ ); \\ represents a literal backslash.

Properties props = new Properties();
props.setProperty("options", "-c search_path=test,public,pg_catalog -c statement_timeout=90000");
Connection conn = DriverManager.getConnection(url, props);

String url = "jdbc:postgresql://localhost:5432/postgres?options=-c%20search_path=test,public,pg_catalog%20-c%20statement_timeout=90000";
Connection conn = DriverManager.getConnection(url);

NOTE

This parameter is ignored when using PKCS-12 keys, since in that case the certificate is also retrieved from the same keyfile.

NOTE

The key file must be in PKCS-12 or in PKCS-8 DER format. A PEM key can be converted to DER format using the openssl command: openssl pkcs8 -topk8 -inform PEM -in postgresql.key -outform DER -out postgresql.pk8 -v1 PBE-MD5-DESWhen you create the key the alias or the name must be user. The test codes uses the following to create a .p12 key openssl pkcs12 -export -in <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>&lt;</mo><mo>−</mo><mi>i</mi><mi>n</mi><mi>k</mi><mi>e</mi><mi>y</mi></mrow><annotation encoding="application/x-tex">&lt; -inkey </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.5782em;vertical-align:-0.0391em;"></span><span class="mrel">&lt;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord">−</span><span class="mord mathnormal" style="margin-right:0.03148em;">ink</span><span class="mord mathnormal" style="margin-right:0.03588em;">ey</span></span></span></span>*.key -out <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">@</mi><mo>−</mo><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mi>u</mi><mi>s</mi><mi>e</mi><mi>r</mi><mo>−</mo><mi>C</mi><mi>A</mi><mi>f</mi><mi>i</mi><mi>l</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">@ -name user -CAfile </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord">@</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.02778em;">ser</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.07153em;">C</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span></span></span></span>(SERVER_CRT_DIR)root.crt -caname local -passout pass:$(P12_PASSWORD)

PKCS-12 key files are only recognized if they have the “.p12” (42.2.9+) or the “.pfx” (42.2.16+) extension.

If your key has a password, provide it using the sslpassword connection parameter described below. Otherwise, you can add the flag -nocrypt to the above command to prevent the driver from requesting a password.

NOTE

The use of -v1 PBE-MD5-DES might be inadequate in environments where high level of security is needed and the key is not protected by other means (e.g. access control of the OS), or the key file is transmitted in untrusted channels. We are depending on the cryptography providers provided by the java runtime. The solution documented here is known to work at the time of writing. If you have stricter security needs, please see here for a discussion of the problem and information on choosing a better cipher suite.

Channel binding is a method for the server to authenticate itself to the client. It is only supported over SSL connections with PostgreSQL 11 or later servers using the SCRAM authentication method.

Unix sockets

By adding junixsocket you can obtain a socket factory that works with the driver. Code can be found here and instructionshere

Dependencies for junixsocket are :

<dependency>
  <groupId>com.kohlschutter.junixsocket</groupId>
  <artifactId>junixsocket-core</artifactId>
  <version>2.5.1</version>
</dependency>

Simply add ?socketFactory=org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg&socketFactoryArg=[path-to-the-unix-socket]to the connection URL.

For many distros the default path is /var/run/postgresql/.s.PGSQL.5432

Connection Fail-over

To support simple connection fail-over it is possible to define multiple endpoints (host and port pairs) in the connection url separated by commas. The driver will try once to connect to each of them in order until the connection succeeds. If none succeeds a normal connection exception is thrown.

The syntax for the connection url is: jdbc:postgresql://host1:port1,host2:port2/database

The simple connection fail-over is useful when running against a high availability postgres installation that has identical data on each node. For example streaming replication postgres or postgres-xc cluster.

For example an application can create two connection pools. One data source is for writes, another for reads. The write pool limits connections only to a primary node:jdbc:postgresql://node1,node2,node3/accounting?targetServerType=primary .

And the read pool balances connections between secondary nodes, but allows connections also to a primary if no secondaries are available: jdbc:postgresql://node1,node2,node3/accounting?targetServerType=preferSecondary&loadBalanceHosts=true

If a secondary fails, all secondaries in the list will be tried first. In the case that there are no available secondaries the primary will be tried. If all the servers are marked as “can’t connect” in the cache then an attempt will be made to connect to all the hosts in the URL, in order.