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:
-
jdbc:postgresql:
database - jdbc:postgresql:/
-
jdbc:postgresql://
host/database -
jdbc:postgresql://
host/ -
jdbc:postgresql://
host:port/database -
jdbc:postgresql://
host:port/
The parameters have the following meanings:
-
hostThe host name of the server. Defaults to
localhost. To specify an IPv6 address your must enclose thehostparameter with square brackets, for example:jdbc:postgresql://[::1]:5740/accounting
-
portThe port number the server is listening on. Defaults to the PostgreSQL standard port number (5432).
-
databaseThe database name. The default is to connect to a database with the same name as the user name.
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)
;
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 a SSL
connection.
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);
-
user = StringThe database user on whose behalf the connection is being made.
-
password = StringThe database user’s password.
-
sslConnect using SSL. The driver must have been compiled with SSL support. This property does not need a value associated with it. The mere presence of it specifies a SSL connection. However, for compatibility with future versions, the value "true" is preferred. For more information see Chapter 4, Using SSL .
-
sslfactory = StringThe provided value is a class name to use as the
SSLSocketFactorywhen establishing a SSL connection. For more information see the section called "Custom SSLSocketFactory" . -
sslfactoryarg = StringThis value is an optional argument to the constructor of the sslfactory class provided above. For more information see the section called "Custom SSLSocketFactory" .
-
sslmode = Stringpossible values are "verify-ca" and "verify-full" setting these will necessitate storing the server certificate on the client machine "Configuring the client" .
-
sslcert = StringProvide the full path for the certificate file. Defaults to /defaultdir/postgresql.crt
Note: defaultdir is ${user.home}/.postgresql/ in *nix systems and %appdata%/postgresql/ on windows
-
sslkey = StringProvide the full path for the key file. Defaults to /defaultdir/postgresql.pk8
-
sslrootcert = StringFile name of the SSL root certificate. Defaults to defaultdir/root.crt
-
sslhostnameverifier = StringClass name of hostname verifier. Defaults to using
org.postgresql.ssl.jdbc4.LibPQFactory.verify() -
sslpaswordcallback = StringClass name of the SSL password provider. Defaults to
org.postgresql.ssl.jdbc4.LibPQFactory.ConsoleCallbackHandler -
sslpassword = StringIf provided will be used by ConsoleCallbackHandler
-
compatible = StringAct like an older version of the driver to retain compatibility with older applications. At the moment this controls two driver behaviours: the handling of binary data fields, and the handling of parameters set via
setString().Older versions of the driver used this property to also control the protocol used to connect to the backend. This is now controlled by the
protocolVersionproperty.Information on binary data handling is detailed in Chapter 7, Storing Binary Data . To force the use of Large Objects set the compatible property to 7.1.
When
compatibleis set to 7.4 or below, the default for thestringtypeparameter is changed tounspecified. -
sendBufferSize = intSets SO_SNDBUF on the connection stream
-
recvBufferSize = intSets SO_RCVBUF on the connection stream
-
protocolVersion = StringThe driver supports the V3 frontend/backend protocols. The V3 protocol was introduced in 7.4 and the driver will by default try to connect using the V3 protocol.
-
loggerLevel = StringLogger level of the driver. Allowed values:
OFF,DEBUGorTRACE. This enable thejava.util.logging.LoggerLevel of the driver based on the following mapping of levels: DEBUG -> FINE, TRACE -> FINEST. This property is intented for debug the driver and not for general SQL query debug. -
loggerFile = StringFile name output of the Logger. If set, the Logger will use a
java.util.logging.FileHandlerto write to a specified file. If the parameter is not set or the file can’t be created thejava.util.logging.ConsoleHandlerwill be used instead. This parameter should be use together with loggerLevel. -
allowEncodingChanges = booleanWhen using the V3 protocol the driver monitors changes in certain server configuration parameters that should not be touched by end users. The
client_encodingsetting is set by the driver and should not be altered. If the driver detects a change it will abort the connection. There is one legitimate exception to this behaviour though, using theCOPYcommand on a file residing on the server’s filesystem. The only means of specifying the encoding of this file is by altering theclient_encodingsetting. The JDBC team considers this a failing of theCOPYcommand and hopes to provide an alternate means of specifying the encoding in the future, but for now there is this URL parameter. Enable this only if you need to override the client encoding when doing a copy. -
logUnclosedConnections = booleanClients may leak
Connectionobjects by failing to call itsclose()method. Eventually these objects will be garbage collected and thefinalize()method will be called which will close theConnectionif caller has neglected to do this himself. The usage of a finalizer is just a stopgap solution. To help developers detect and correct the source of these leaks thelogUnclosedConnectionsURL parameter has been added. It captures a stacktrace at eachConnectionopening and if thefinalize()method is reached without having been closed the stacktrace is printed to the log. -
autoCloseUnclosedStatements = booleanClients may leak
Statementobjects by failing to call itsclose()method. IfautoCloseUnclosedStatementsis set to "true" then finalizer will be used as a stopgap solution toclose()the resource.Note: Creating finalizable objects is very expensive in lots of JVM. It dramatically impacts
Statementinstantiation and increases time spent in garbage collection, so avoid usingautoCloseUnclosedStatements="true" for highly loaded applications unless you are sure your JVM can crater finalizer traffic. -
binaryTransferEnable = StringA comma separated list of types to enable binary transfer. Either OID numbers or names.
-
binaryTransferDisable = StringA comma separated list of types to disable binary transfer. Either OID numbers or names. Overrides values in the driver default set and values set with binaryTransferEnable.
-
prepareThreshold = intDetermine the number of
PreparedStatementexecutions required before switching over to use server side prepared statements. The default is five, meaning start using server side prepared statements on the fifth execution of the samePreparedStatementobject. More information on server side prepared statements is available in the section called "Server Prepared Statements" . -
preparedStatementCacheQueries = intDetermine the number of queries that are cached in each connection. The default is 256, meaning if you use more than 256 different queries inprepareStatement()calls, the least recently used ones will be discarded. The cache allows application to benefit from "Server Prepared Statements" (seeprepareThreshold) even if the prepared statement is closed after each execution. The value of 0 disables the cache.N.B.Each connection has its own statement cache.
-
preparedStatementCacheSizeMiB = intDetermine the maximum size (in mebibytes) of the prepared queries cache (see
preparedStatementCacheQueries). The default is 5, meaning if you happen to cache more than 5 MiB of queries the least recently used ones will be discarded. The main aim of this setting is to preventOutOfMemoryError. The value of 0 disables the cache. -
defaultRowFetchSize = intDetermine the number of rows fetched in
ResultSetby one fetch with trip to the database. Limiting the number of rows are fetch with each trip to the database allow avoids unnecessary memory consumption and as a consequenceOutOfMemoryException.The default is zero, meaning that in
ResultSetwill be fetch all rows at once. Negative number is not available. -
loginTimeout = intSpecify how long to wait for establishment of a database connection. The timeout is specified in seconds.
-
connectTimeout = int
The timeout value used for socket connect operations. If connecting to the server takes longer than this value, the connection is broken. The timeout is specified in seconds and a value of zero means that it is disabled.
-
socketTimeout = intThe timeout value used for socket read operations. If reading from the server takes longer than this value, the connection is closed. This can be used as both a brute force global query timeout and a method of detecting network problems. The timeout is specified in seconds and a value of zero means that it is disabled.
-
tcpKeepAlive = booleanEnable or disable TCP keep-alive probe. The default is
false. -
unknownLength = intCertain postgresql types such as
TEXTdo not have a well defined length. When returning meta-data about these types through functions likeResultSetMetaData.getColumnDisplaySizeandResultSetMetaData.getPrecisionwe must provide a value and various client tools have different ideas about what they would like to see. This parameter specifies the length to return for types of unknown length. -
stringtype = StringSpecify the type to use when binding
PreparedStatementparameters set viasetString(). Ifstringtypeis set toVARCHAR(the default), such parameters will be sent to the server as varchar parameters. Ifstringtypeis set tounspecified, parameters will be sent to the server as untyped values, and the server will attempt to infer an appropriate type. This is useful if you have an existing application that usessetString()to set parameters that are actually some other type, such as integers, and you are unable to change the application to use an appropriate method such assetInt(). -
kerberosServerName = StringThe Kerberos service name to use when authenticating with GSSAPI. This is equivalent to libpq’s PGKRBSRVNAME environment variable and defaults to "postgres".
-
jaasApplicationName = StringSpecifies the name of the JAAS system or application login configuration.
-
ApplicationName = StringSpecifies the name of the application that is using the connection. This allows a database administrator to see what applications are connected to the server and what resources they are using through views like pg_stat_activity.
-
gsslib = StringForce either SSPI (Windows transparent single-sign-on) or GSSAPI (Kerberos, via JSSE) to be used when the server requests Kerberos or SSPI authentication. Permissible values are auto (default, see below), sspi (force SSPI) or gssapi (force GSSAPI-JSSE).
If this parameter is auto, SSPI is attempted if the server requests SSPI authentication, the JDBC client is running on Windows, and the Waffle libraries required for SSPI are on the CLASSPATH. Otherwise Kerberos/GSSAPI via JSSE is used. Note that this behaviour does not exactly match that of libpq, which uses Windows’ SSPI libraries for Kerberos (GSSAPI) requests by default when on Windows.
gssapi mode forces JSSE’s GSSAPI to be used even if SSPI is available, matching the pre-9.4 behaviour.
On non-Windows platforms or where SSPI is unavailable, forcing sspi mode will fail with a PSQLException.
Since: 9.4
-
sspiServiceClass = StringSpecifies the name of the Windows SSPI service class that forms the service class part of the SPN. The default, POSTGRES, is almost always correct.
See: SSPI authentication (Pg docs) Service Principal Names (MSDN), DsMakeSpn (MSDN) Configuring SSPI (Pg wiki).
This parameter is ignored on non-Windows platforms.
-
useSpnego = booleanUse SPNEGO in SSPI authentication requests
-
sendBufferSize = intSets SO_SNDBUF on the connection stream
-
receiveBufferSize = intSets SO_RCVBUF on the connection stream
-
readOnly = booleanPut the connection in read-only mode
-
disableColumnSanitiser = booleanEnable optimization that disables column name sanitiser.
-
assumeMinServerVersion = StringAssume that the server is at least the given version, thus enabling to some optimization at connection time instead of trying to be version blind.
-
currentSchema = StringSpecify the schema to be set in the search-path. This schema will be used to resolve unqualified object names used in statements over this connection.
-
targetServerTypeAllows opening connections to only servers with required state, the allowed values are any, master, slave and preferSlave. The master/slave distinction is currently done by observing if the server allows writes. The value preferSlave tries to connect to slaves if any are available, otherwise allows falls back to connecting also to master.
-
hostRecheckSeconds = intControls how long in seconds the knowledge about a host state is cached in JVM wide global cache. The default value is 10 seconds.
-
loadBalanceHosts = booleanIn default mode (disabled) hosts are connected in the given order. If enabled hosts are chosen randomly from the set of suitable candidates.
-
socketFactory = StringThe provided value is a class name to use as the
SocketFactorywhen establishing a socket connection. This may be used to create unix sockets instead of normal sockets. The class name specified bysocketFactorymust extendjavax.net.SocketFactoryand be available to the driver’s classloader. This class must have a zero argument constructor or a single argument constructor taking a String argument. This argument may optionally be supplied bysocketFactoryArg. -
socketFactoryArg = StringThis value is an optional argument to the constructor of the socket factory class provided above.
-
reWriteBatchedInserts=trueThis will change batch inserts from insert into foo (col1, col2, col3) values (1,2,3) into insert into foo (col1, col2, col3) values (1,2,3), (4,5,6) this provides 2-3x performance improvement
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 to once connect to each of them in order until the connection succeeds. If none succeed, 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 master node:
jdbc:postgresql://node1,node2,node3/accounting?targetServerType=master . And read pool balances connections between slaves nodes, but allows connections also to master if no slaves are available:
jdbc:postgresql://node1,node2,node3/accounting?targetServerType=preferSlave&loadBalanceHosts=true