Server preparation
Three things to verify on the server side before a Java application can connect. None of them are pgJDBC-specific (they are PostgreSQL configuration tasks), but each one is a common reason for an otherwise correct application to fail at startup.
The server listens on TCP
Java cannot connect over a Unix-domain socket without an extra library (see Unix sockets ). For TCP, the server must be configured to accept it.
# postgresql.conf — accept connections on all interfaces
listen_addresses = '*'
The default is localhost, which is fine for an application running on
the same host as the database; for anything else, broaden the address
or list specific interfaces. Restart PostgreSQL after editing.
pg_hba.conf allows the connection
Even with the listener open, PostgreSQL refuses authentication for
client/database/host combinations that are not explicitly permitted.
The relevant file is pg_hba.conf in the server’s data directory.
A minimal SCRAM-secured rule for a remote application:
# TYPE DATABASE USER ADDRESS METHOD
host mydb alice 10.0.0.0/16 scram-sha-256
hostssl mydb alice 0.0.0.0/0 scram-sha-256
The full reference is the PostgreSQL
pg_hba.conf documentation
.
Use hostssl (not host) for any non-local rule so plaintext rows
never apply over the network; pair it with sslmode=verify-full on
the client side (see Configure SSL/TLS (in Quick start)
).
Database encoding is UTF-8
CREATE DATABASE mydb WITH ENCODING 'UTF8';
Java strings are UTF-16 internally and the driver converts to whatever
the database’s client_encoding is. With a UTF-8 database the round-trip
is lossless except for two cases:
- PostgreSQL rejects the NUL byte (
U+0000) in any text column. - Java strings with unpaired UTF-16 surrogates have no valid UTF-8 encoding and cannot be sent.
Avoid SQL_ASCII. It is not a real encoding (it accepts any byte
sequence without validation), and you will hit corruption the first
time the application stores a character outside seven-bit ASCII.
Next step
With those three boxes ticked, return to the Quick start and open the first connection.