Using JDBC to Connect to a Database

Obtaining the Driver Package

Download the GaussDB driver package GaussDB_opengauss_client_tools.zip.

Prerequisites

Java JDK 8 has been installed on the local PC.

You can load the driver using either of the following ways:

  • Before creating a connection, implicitly load the driver in the code: Class.forName("org.postgresql.Driver")

  • During the JVM startup, transfer the driver as a parameter to JVM: java -Djdbc.drivers=org.postgresql.Driver jdbctest

    Note

    jdbctest is the name of a test application.

Calling a Function to Create a Database Connection

JDBC provides the following three database connection methods:

  • DriverManager.getConnection(String url);

  • DriverManager.getConnection(String url, Properties info);

  • DriverManager.getConnection(String url, String user, String password);

For details about connection parameters of distributed and primary/standby DB instances, see Table 1 and Table 2, respectively.

Table 1 Connection parameters of distributed DB instances

Parameter

Description

url

gsjdbc4.jar database connection descriptor. The format is as follows:

Note

If gsjdbc200.jar is used, change jdbc:postgresql to jdbc:gaussdb.

  • database: name of the database to be connected.

  • host: name or IP address of the database server.

    It is recommended that the service system be deployed outside the DB instance. If it is deployed inside, the database performance may be affected.

    If the host is not specified, localhost is used by default.

  • port: the port number that the database server is listening on.

    By default, JDBC tries to connect to the database through port 5432.

  • param: database connection attribute.

    Parameters can be configured in the URL. The URL starts with a question mark (?), uses the equal sign (=) to assign values to parameters, and use the ampersand (&) to separate parameters. Alternatively, use the attributes of the info object to configure parameters. For details, see the example below.

  • value: database connection attribute value.

  • connectTimeout and socketTimeout must be configured for connection. The recommended value is 2. The default value is 0, indicating that the connection will not time out. When the network between a DN and the client is faulty, the client does not receive ACK packets from the DN. In this case, the client starts the timeout retransmission mechanism to continuously retransmit packets. A timeout error is reported only when the timeout interval reaches the default value 600s. As a result, the RTO is high.

info

Database connection attributes (all attributes are case-sensitive). Common attributes are as follows:

PGDBNAME: string type. This parameter indicates the database name, which is automatically parsed from the URL.

PGHOST: string type. This parameter indicates the host IP address. Use colons (:) to separate IP addresses and port numbers, and use commas (,) to separate multiple IP addresses. (This parameter does not need to be configured in the URL. The system automatically parses the URL to obtain its value.)

PGPORT: integer type. This parameter indicates the host port number. Use colons (:) to separate IP addresses and port numbers, and use commas (,) to separate multiple IP addresses. (This parameter does not need to be set in the URL. The system automatically parses the URL to obtain its value.)

user: string type. This parameter indicates the database user who creates the connection.

password: string type. This parameter indicates the password of a database user.

loggerLevel: string type. Currently, four log levels are supported: OFF, INFO, DEBUG, and TRACE. If this parameter is set to OFF, the log function is disabled. If this parameter is set to INFO, DEBUG, and TRACE, the log information of different levels is recorded.

loggerFile: string type. This parameter indicates the log output path (including directory and file name). If only the file name is specified and the directory is not specified, logs are stored in the directory where the client program is running. If no path is configured or the configured path does not exist, logs are output through flows by default.

logger: string type. This parameter indicates the log output framework used by the JDBC driver for interconnecting with user applications. Currently, only the third-party SLF4J API-based log framework is supported.

  • If this parameter is not set or is set to JDK LOGGER, JDK LOGGER is used.

  • Otherwise, the third-party SLF4J API-based log framework is used.

allowEncodingChanges: Boolean type. If this parameter is set to true, the character set type can be changed. This parameter is used together with characterEncoding=CHARSET to set the character set. The two parameters are separated by ampersands (&).

currentSchema: string type. This parameter indicates the schema to be set in search-path.

loadBalanceHosts: Boolean type. If load balancing is disabled (by default), multiple hosts specified in the URL are connected in sequence. If load balancing is enabled, the shuffle algorithm is used to randomly select a host from the candidate hosts to establish a connection.

autoBalance: string type.

  • If this parameter is set to true, balance, or roundrobin, load balancing is enabled to balance multiple connections of an application to each available node.

    Example: jdbc:postgresql://host1:port1,host2:port2/database?autoBalance=true

    JDBC periodically obtains the list of available CNs of a DB instance, for example, the obtained list is host1:port1,host2:port2,host3:port3,host4:port4. The refreshCNIpListTime parameter specifies the interval for obtaining the list, and the default value is 10s.

    In the first connection, only HA is implemented with autoBalance enabled in host1 and host2. In non-first connection, the JDBC driver will select available CNs from host1, host2, host3, and host4 in sequence to update the available CN list and new connections will be established on host1, host2, host3, and host4 using the RoundRobin algorithm.

  • priorityn indicates that priority-based load balancing is enabled. Multiple connections of an application are balanced to the first n available primary CNs configured in the URL. When the first n CNs are unavailable, connections are randomly allocated to other available CNs in the DB instance. n is a number, which must be at least 0 and less than the number of CNs configured in the URL.

    Example: jdbc:postgresql://host1:port1,host2:port2,host3:port3,host4:port4/database?autoBalance=priority2

    JDBC periodically obtains the list of available CNs of an instance. The refreshCNIpListTime parameter specifies the interval for obtaining the list. For example, if the obtained list is host1:port1,host2:port2,host3:port3,host4:port4,host5:port5,host6:port6, the driver preferentially selects host1 and host2 for load balancing. If both host1 and host2 are unavailable, the driver then randomly selects a CN from host3, host4, host5, and host6 for connection.

  • If this parameter is set to shuffle, random-based load balancing is enabled. Multiple connections of the application are randomly and evenly distributed to available CNs of a DB instance.

    Example: jdbc:postgresql://host1:port1,host2:port2,host3:port3/database?autoBalance=shuffle

    JDBC periodically obtains the list of available CNs of a DB instance, for example, the obtained list is host1:port1,host2:port2,host3:port3,host4:port4. The refreshCNIpListTime parameter specifies the interval for obtaining the list, and the default value is 10s.

    For the first connection, host1:port1,host2:port2,host3:port3 is used for HA. For subsequent connections, the shuffle algorithm is used to randomly select a CN from the refreshed CN list.

  • If this parameter is set to false, load balancing is disabled. The default value is false.

    Caution

    CAUTION: Load balancing is based on the connection level rather than the transaction level. If the connection is persistent and the load on the connection is unbalanced, the load on CNs may be unbalanced.

    Load balancing can be used only for distributed DB instances.

    When priorityn is used for load balancing, the IP address in the connection string must be the same as the value of node_host of the CN in the pgxc_node table. Otherwise, priority-based load balancing cannot be implemented.

    To query the IP address and port number of an available CN of a DB instance, run the select node_host,node_port from pgxc_node where node_type='C' and nodeis_active = true; statement.

refreshCNIpListTime: integer type. JDBC periodically obtains the list of available CNs of a DB instance. This parameter indicates the interval for obtaining the list. The default value is 10s.

hostRecheckSeconds: integer type. After JDBC attempts to connect to a host, the host status is saved: connection success or connection failure. This status is trusted within the duration specified by hostRecheckSeconds. After the duration expires, the status becomes invalid. The default value is 10s.

ssl: Boolean type. This parameter indicates SSL connection.

When this parameter is set to true, NonValidatingFactory and certificate authentication are supported.

  • For NonValidatingFactory, configure the username and password.

  • For certification authentication, configure the client certificate, key, and root certificate.

sslmode: string type. This parameter indicates the SSL authentication mode. The value can be require, verify-ca, or verify-full.

  • require: The system attempts to set up an SSL connection. It neither checks whether the server certificate is issued by a trusted CA, nor checks whether the host name of the server is the same as that in the certificate.

  • verify-ca: The system attempts to set up an SSL connection and checks whether the server certificate is issued by a trusted CA.

  • verify-full: The system attempts to set up an SSL connection, checks whether the server certificate is issued by a trusted CA, and checks whether the host name of the server is the same as that in the certificate.

sslcert: string type. This parameter indicates the complete path of the certificate file. The type of the client and server certificates is End Entity.

sslkey: string type. This parameter indicates the complete path of the key file.

sslrootcert: string type. This parameter indicates the name of the SSL root certificate. The root certificate type is CA.

sslpassword: string type. This parameter is suitable for ConsoleCallbackHandler.

sslpasswordcallback: string type. This parameter indicates the class name of the SSL password provider. The default value is org.postgresql.ssl.jdbc4.LibPQFactory.ConsoleCallbackHandler.

sslfactory: string type. This parameter indicates the class name used by SSLSocketFactory to establish an SSL connection.

sslprivatekeyfactory: string type. This parameter indicates the fully qualified name of the implementation class of the org.postgresql.ssl.PrivateKeyFactory interface that implements the private key decryption method. If this parameter is not specified, use default JDK private key decryption algorithm. If the decryption fails, use org.postgresql.ssl.BouncyCastlePrivateKeyFactory. You need to provide the bcpkix-jdk15on.jar package. The recommended version is 1.65 or later.

sslfactoryarg: string type. It is an optional parameter of sslfactory constructors and is not recommended.

sslhostnameverifier: string type. This parameter indicates the class name of the host name verifier. The javax.net.ssl.HostnameVerifier interface can be implemented. The default value is org.postgresql.ssl.PGjdbcHostnameVerifier.

loginTimeout: integer type. This parameter indicates the waiting time for establishing the database connection, in seconds.

connectTimeout: integer type. This parameter indicates the timeout duration for connecting to a server. If the time taken to connect to a server exceeds the value specified, the connection is interrupted. If the value is 0, the timeout mechanism is disabled.

socketTimeout: integer type. This parameter indicates the timeout duration for a socket read operation. If the time taken to read data from a server exceeds the value specified, the connection is closed. If the value is 0, the timeout mechanism is disabled.

cancelSignalTimeout: integer type. Canceling messages may get stuck. This parameter controls connectTimeout and socketTimeout used for cancel commends, in seconds. The default value is 10s.

tcpKeepAlive: Boolean type. This parameter is used to enable or disable TCP keep-alive probe. The default value is false.

logUnclosedConnections: Boolean type. A client may leak a connection object because it does not call the connection object's close() method. The object will be collected as garbage and finalized using the finalize() method. If the caller ignores this operation, this parameter is used to close the connection.

assumeMinServerVersion (deprecated): string type. This parameter indicates the version of the server to be connected.

ApplicationName: string type. This parameter indicates the name of the application that is being connected. You can query the pgxc_stat_activity table to view information about the client that is being connected. The parameter value is displayed in the application_name column. The default value is PostgreSQL JDBC Driver.

connectionExtraInfo: Boolean type. This parameter indicates whether the JDBC driver reports the driver deployment path and process owner to the database.

The value can be true or false. The default value is false. If connectionExtraInfo is set to true, the JDBC driver reports the driver deployment path and process owner to the database. The connection_info parameter indicates the reported information. In this case, you can query the information from PG_STAT_ACTIVITY or PGXC_STAT_ACTIVITY.

autosave: string type. The value can be always, never, or conservative. This parameter indicates what the driver should do upon a query failure. If autosave is set to always, the JDBC driver sets a savepoint before each query and rolls back to the savepoint if the query fails. If autosave is set to never, there is no savepoint. If autosave is set to conservative, a savepoint is set for each query. However, the rollback and retries are done only when there is an invalid statement.

protocolVersion: integer type. This parameter indicates the connection protocol version. Only version 3 is supported. When this parameter is specified, you must change the database encryption mode (by running gs_guc set -N all -I all -Z coordinator -c "password_encryption_type=1") and use MD5 encryption. After the DB instance is rebooted, create a user that uses MD5 encryption to encrypt passwords. You must also change the client connection mode to md5 in pg_hba.conf. Log in to the system as the new user. (You are not advised to specify this parameter because the MD5 encryption algorithm has lower security and poses security risks.)

Note

MD5 encryption is less secure and is not recommended.

prepareThreshold: integer type. This parameter indicates the number of times that the PreparedStatement object is executed before the prepared statement on the server is used. The default value is 5, indicating that when the same PreparedStatement object is executed for five or more times, the parse message is not sent to the server to parse the statement. Instead, the statement that has been parsed on the server is used.

preparedStatementCacheQueries: integer type. This parameter indicates the maximum number of queries that are cached in each connection. The default value is 256. If you use more than 256 different queries in prepareStatement() calls, the least recently used queries will be discarded from the cache. The value 0 indicates the cache function is disabled.

preparedStatementCacheSizeMiB: integer type. This parameter indicates the maximum size of queries generated by the cache statement object of each connection, in MB. The default value is 5. If you cache more than 5 MB of queries, the least recently used queries will be discarded. The value 0 indicates the cache function is disabled.

databaseMetadataCacheFields: integer type. The default value is 65536. This parameter specifies the maximum number of columns that can be cached in each connection. The value 0 indicates the cache function is disabled.

databaseMetadataCacheFieldsMiB: integer type. The default value is 5. This parameter indicates the maximum size of fields that can be cached in each connection, in MB. The value 0 indicates the cache function is disabled.

stringtype: string type. The value can be unspecified or varchar. This parameter indicates the type to use when binding PreparedStatement parameters set via setString(). If stringtype is set to VARCHAR (the default value), such parameters will be sent to the server as varchar parameters. If stringtype is set to unspecified, parameters are sent to the server as untyped values, and the server attempts to infer an appropriate type.

batchMode: Boolean type. This parameter indicates whether to connect the database in batch mode. The default value is on, indicating that the batch mode is enabled.

fetchsize: integer type. This parameter indicates the default fetchsize for statements in the created connection. The value 0 (by default) indicates that all results are obtained at a time.

reWriteBatchedInserts: Boolean type. During batch import, if this parameter is set to on, N insertion statements can be combined into one: insert into TABLE_NAME values(values1, ..., valuesN), ..., (values1, ..., valuesN). To use this parameter, set batchMode to off.

unknownLength: integer type. The default value is Integer.MAX_VALUE. This parameter specifies the length of the unknown length type when the data of some PostgreSQL types (such as TEXT) is returned by functions such as ResultSetMetaData.getColumnDisplaySize and ResultSetMetaData.getPrecision.

defaultRowFetchSize: integer type. This parameter indicates the number of rows read by fetch in ResultSet at a time. Limiting the number of rows read each time in a database access request can avoid unnecessary memory consumption, thereby avoiding out of memory exception. The default value is 0, indicating that all rows are obtained at a time in ResultSet. This parameter cannot be set to a negative value.

binaryTransfer: Boolean type. This parameter indicates whether data is sent and received in binary format. The default value is false.

binaryTransferEnable: string type. This parameter indicates the type for which binary transmission is enabled. Every two types are separated by commas (,). You can select either the OID number or name, for example, binaryTransferEnable=INT4_ARRAY,INT8_ARRAY.

For example, if the OID name is BLOB and the OID number is 88, you can configure the OID as follows:

binaryTransferEnable=BLOB or binaryTransferEnable=88

binaryTransferDisEnable: string type. This parameter indicates the type for which binary transmission is disabled. Every two types are separated by commas (,). You can select either the OID number or name. The value of this parameter overwrites the value of binaryTransferEnable.

blobMode: string type. This parameter is used to make the setBinaryStream(int, InputStream, int) method assign values to different types of data. The value on indicates that values are assigned to BLOB data type. The value off indicates that values are assigned to BYTEA data type. The default value is on. setBinaryStream(int, InputStream, long) and setBinaryStream(int, InputStream) are used to assign values to the BYTEA data type.

socketFactory: string type. This parameter indicates the name of the class used to create a socket connection with the server. This class must extend javax.net.SocketFactory and define a constructor with no parameter or a single string parameter.

socketFactoryArg: string type. It is an optional parameter of the constructor of the socketFactory class and is not recommended.

receiveBufferSize: integer type. This parameter is used to specify SO_RCVBUF on the connection stream.

sendBufferSize: integer type. This parameter is used to specify SO_SNDBUF on the connection stream.

preferQueryMode: string type. The value can be extended, extendedForPrepared, extendedCacheEverything, or simple. This parameter indicates the query mode. The default value is extended. In simple mode, only the Q message in text mode can be sent. The parse and bind messages are not supported. In extended mode, parse, bind, and execute messages are used. In extendedForPrepared mode, only the prepared statement object uses extended query, and the statement object uses only simple query. The extendedCacheEverything mode caches the query generated by each statement object.

ApplicationType: string type. The value can be not_perfect_sharding_type or perfect_sharding_type. This parameter indicates whether to enable distributed write and query. If this parameter is set to not_perfect_sharding_type (default value), distributed write and query are enabled. If it is set to perfect_sharding_type, distributed write and query are disabled. However, distributed write and query can be performed only when /* multinode */ is added to the SQL statement. This parameter is valid only when the database is in the GTM-free scenario.

user

Database user.

password

Password of the database user.

Table 2 Connection parameters of primary/standby DB instances

Parameter

Description

url

postgresql.jar database connection descriptor. The format is as follows:

Note

  • database: name of the database to be connected.

  • host: name or IP address of the database server.

    For security purposes, the primary database node forbids unauthorized access from other nodes in the database. To access the primary database node from inside the database, deploy the JDBC program on the host where the primary database node is located and set host to 127.0.0.1. If you do not do so, the error message "FATAL: Forbid remote connection with trust method!" may be displayed.

    It is recommended that the service system be deployed outside the database. Otherwise, the database performance may be affected.

    If the host is not specified, localhost is used by default.

  • port: the port number that the database server is listening on.

    By default, JDBC tries to connect to the database through port 5432.

  • param: database connection attribute.

    Parameters can be configured in the URL. The URL starts with a question mark (?), uses the equal sign (=) to assign values to parameters, and use the ampersand (&) to separate parameters. Alternatively, use the attributes of the info object to configure parameters. For details, see the example below.

  • value: database connection attribute value.

  • connectTimeout and socketTimeout must be configured for connection. The recommended value is 2. The default value is 0, indicating that the connection will not time out. When the network between a DN and the client is faulty, the client does not receive ACK packets from the DN. In this case, the client starts the timeout retransmission mechanism to continuously retransmit packets. A timeout error is reported only when the timeout interval reaches the default value 600s. As a result, the RTO is high.

info

Database connection attributes (all attributes are case-sensitive). Common attributes are as follows:

  • PGDBNAME: string type. This parameter indicates the database name. (This parameter does not need to be specified in the URL. The system automatically parses the URL to obtain its value.)

  • PGHOST: string type. This parameter indicates the host IP address. For details, see the following example.

  • PGPORT: integer type. This parameter indicates the host port number. For details, see the following example.

  • user: string type. This parameter indicates the database user who creates the connection.

  • password: string type. This parameter indicates the password of a database user.

  • loggerLevel: string type. The following log levels are supported: OFF, DEBUG, and TRACE. The value OFF indicates that the log function is disabled. DEBUG and TRACE log record information of different levels.

  • loggerFile: string type. This parameter indicates the name of a log file. You can specify a directory for storing logs. If no directory is specified, logs are stored in the directory where the client program is running.

  • allowEncodingChanges: Boolean type. If this parameter is set to true, the character set type can be changed. This parameter is used together with characterEncoding=CHARSET to set the character set. The two parameters are separated by ampersands (&).

  • currentSchema: string type. This parameter indicates the schema to be set in search-path.

  • hostRecheckSeconds: integer type. After JDBC attempts to connect to a host, the host status is saved: connection success or connection failure. This status is trusted within the duration specified by hostRecheckSeconds. After the duration expires, the status becomes invalid. The default value is 10s.

  • ssl: Boolean type. This parameter indicates SSL connection.

    When this parameter is set to true, NonValidatingFactory and certificate authentication are supported.

    For NonValidatingFactory, configure the username and password.

    For certification authentication, configure the client certificate, key, and root certificate.

  • sslmode: string type. This parameter indicates the SSL authentication mode. The value can be require, verify-ca, or verify-full.

    • require: The system attempts to set up an SSL connection. If there is a CA file, the system performs verification when the parameter is set to verify-ca.

    • verify-ca: The system attempts to set up an SSL connection and checks whether the server certificate is issued by a trusted CA.

    • verify-full: The system attempts to set up an SSL connection, checks whether the server certificate is issued by a trusted CA, and checks whether the host name of the server is the same as that in the certificate.

  • sslcert: string type. This parameter indicates the complete path of the certificate file. The type of the client and server certificates is End Entity.

  • sslkey: string type. This parameter indicates the complete path of the key file. You must run the following command to convert the client certificate to the DER format:

    openssl pkcs8 -topk8 -outform DER -in client.key -out client.key.pk8 -nocrypt
    
  • sslrootcert: string type. This parameter indicates the name of the SSL root certificate. The root certificate type is CA.

  • sslpassword: string type. This parameter is suitable for ConsoleCallbackHandler.

  • sslpasswordcallback: string type. This parameter indicates the class name of the SSL password provider. The default value is org.postgresql.ssl.jdbc4.LibPQFactory.ConsoleCallbackHandler.

  • sslfactory: string type. This parameter indicates the class name used by SSLSocketFactory to establish an SSL connection.

  • sslfactoryarg: string type. It is an optional parameter of sslfactory constructors and is not recommended.

  • sslhostnameverifier: string type. This parameter indicates the class name of the host name verifier. The javax.net.ssl.HostnameVerifier interface can be implemented. The default value is org.postgresql.ssl.PGjdbcHostnameVerifier.

  • loginTimeout: integer type. This parameter indicates the waiting time for establishing the database connection, in seconds.

  • connectTimeout: integer type. This parameter indicates the timeout duration for connecting to a server. If the time taken to connect to a server exceeds the value specified, the connection is interrupted. If the value is 0, the timeout mechanism is disabled.

  • socketTimeout: integer type. This parameter indicates the timeout duration for a socket read operation. If the time taken to read data from a server exceeds the value specified, the connection is closed. If the value is 0, the timeout mechanism is disabled.

  • cancelSignalTimeout: integer type. Canceling messages may get stuck. This parameter controls connectTimeout and socketTimeout used for cancel commends, in seconds. The default value is 10s.

  • tcpKeepAlive: Boolean type. This parameter is used to enable or disable TCP keep-alive probe. The default value is false.

  • logUnclosedConnections: Boolean type. A client may leak a connection object because it does not call the connection object's close() method. The object will be collected as garbage and finalized using the finalize() method. If the caller ignores this operation, this parameter is used to close the connection.

  • assumeMinServerVersion: string type. The client sends a request to set a floating point. This parameter indicates the version of the server to connect, for example, assumeMinServerVersion=9.0. This parameter can reduce the number of packets to send during connection setup.

  • ApplicationName: string type. This parameter indicates the name of the JDBC driver that is being connected. You can query the pg_stat_activity table on the primary database node to view information about the client that is being connected. The JDBC driver name is displayed in the application_name column. The default value is PostgreSQL JDBC Driver.

  • connectionExtraInfo: Boolean type. This parameter indicates whether the JDBC driver reports the driver deployment path and process owner to the database.

    The value can be true or false. The default value is false. If connectionExtraInfo is set to true, the JDBC driver reports the driver deployment path and process owner to the database and the reported information is stored in connection_info. In this case, you can query the information from PG_STAT_ACTIVITY.

  • autosave: string type. The value can be always, never, or conservative. This parameter indicates what the driver should do upon a query failure. If autosave is set to always, the JDBC driver sets a savepoint before each query and rolls back to the savepoint if the query fails. If autosave is set to never, there is no savepoint. If autosave is set to conservative, a savepoint is set for each query. However, the rollback and retries are done only when there is an invalid statement.

  • protocolVersion: integer type. This parameter indicates the connection protocol version. Only version 3 is supported. When this parameter is specified, you must change the database encryption mode (by running gs_guc set -N all -I all -c "password_encryption_type=1") and use MD5 encryption. After the database is rebooted, create a user that uses MD5 encryption to encrypt passwords. You must also change the client connection mode to md5 in pg_hba.conf. Log in as the new user (not recommended).

    Note

    MD5 encryption is less secure and is not recommended.

  • prepareThreshold: integer type. This parameter indicates the time when the parse statement is sent. The default value is 5. It takes a long time to parse an SQL statement for the first time, but a short time to parse SQL statements later because of cache. If a session runs an SQL statement multiple consecutive times and the number of execution times exceeds the value of prepareThreshold, JDBC does not send the parse command to the SQL statement.

  • preparedStatementCacheQueries: integer type. This parameter indicates the number of queries cached in each connection. The default value is 256. If more than 256 different queries are used in prepareStatement() calls, the least recently used queries will be discarded. The value 0 indicates the cache function is disabled.

  • preparedStatementCacheSizeMiB: integer type. This parameter indicates the maximum cache size of each connection, in MB. The default value is 5. If you cache more than 5 MB of queries, the least recently used queries will be discarded. The value 0 indicates the cache function is disabled.

  • databaseMetadataCacheFields: integer type. The default value is 65536. This parameter indicates the maximum cache size of each connection. The value 0 indicates the cache function is disabled.

  • databaseMetadataCacheFieldsMiB: integer type. The default value is 5. This parameter indicates the maximum cache size of each connection, in MB. The value 0 indicates the cache function is disabled.

  • stringtype: string type. The value can be false, unspecified, or varchar. This parameter indicates the type to use when binding PreparedStatement parameters set via setString(). If stringtype is set to VARCHAR (the default value), such parameters will be sent to the server as varchar parameters. If stringtype is set to unspecified, parameters are sent to the server as untyped values, and the server attempts to infer an appropriate type.

  • batchMode: Boolean type. This parameter indicates whether to connect the database in batch mode. The default value is on, indicating that the batch mode is enabled.

  • fetchsize: integer type. This parameter indicates the default fetchsize for statements in the created connection. The value 0 (by default) indicates that all results are obtained at a time.

  • reWriteBatchedInserts: Boolean type. During batch import, if this parameter is set to on, N insertion statements can be combined into one: insert into TABLE_NAME values(values1, ..., valuesN), ..., (values1, ..., valuesN). To use this parameter, set batchMode to off.

  • unknownLength: integer type. The default value is Integer.MAX_VALUE. This parameter specifies the length of the unknown length type when the data of some PostgreSQL types (such as TEXT) is returned by functions such as ResultSetMetaData.getColumnDisplaySize and ResultSetMetaData.getPrecision.

  • defaultRowFetchSize: integer type. This parameter indicates the number of rows read by fetch in ResultSet at a time. Limiting the number of rows read each time in a database access request can avoid unnecessary memory consumption, thereby avoiding out of memory exception. The default value is 0, indicating that all rows are obtained at a time in ResultSet. It cannot be a negative value.

  • binaryTransfer: Boolean type. This parameter indicates whether data is sent and received in binary format. The default value is false.

  • binaryTransferEnable: string type. This parameter indicates the type for which binary transmission is enabled. Every two types are separated by commas (,). You can select either the OID or name, for example, binaryTransferEnable=Integer4_ARRAY,Integer8_ARRAY.

    For example, if the OID name is BLOB and the OID number is 88, you can configure the OID as follows:

    binaryTransferEnable=BLOB or binaryTransferEnable=88

  • binaryTransferDisEnable: string type. This parameter indicates the type for which binary transmission is disabled. Every two types are separated by commas (,). You can select either the OID number or name. The value of this parameter overwrites the value of binaryTransferEnable.

  • blobMode: string type. This parameter is used to make the setBinaryStream method assign values to different types of data. The value on indicates that values are assigned to the BLOB data type. The value off indicates that values are assigned to the BYTEA data type. The default value is on.

  • socketFactory: string type. This parameter indicates the name of the class used to create a socket connection with the server. This class must extend javax.net.SocketFactory and define a constructor with no parameter or a single string parameter.

  • socketFactoryArg: string type. It is an optional parameter of the constructor of the socketFactory class and is not recommended.

  • receiveBufferSize: integer type. This parameter is used to specify SO_RCVBUF on the connection stream.

  • sendBufferSize: integer type. This parameter is used to specify SO_SNDBUF on the connection stream.

  • preferQueryMode: string type. The value can be extended, extendedForPrepared, extendedCacheEverything, or simple. This parameter indicates the query mode. In simple mode, the query is executed without parsing or binding. In extended mode, the query is executed and bound. The extendedForPrepared mode is used for prepared statement extension. In extendedCacheEverything mode, each statement is cached.

  • targetServerType: string type. This parameter is used to identify the primary DN and standby DN by querying whether a DN allows the write operation in the URL connection string. The default value is any. The value can be any, master, slave, or preferSlave.

    • master: attempts to connect to a primary DN in the URL connection string. If the primary DN cannot be found, an exception is thrown.

    • slave: attempts to connect to a standby DN in the URL connection string. If the standby DN cannot be found, an exception is thrown.

    • preferSlave: attempts to connect to a standby DN (if available) in the URL connection string. Otherwise, it connects to the primary DN.

    • any: attempts to connect to any DN in the URL connection string.

user

Database user.

password

Password of the database user.

Example

// The following code encapsulates database connection operations into an interface. The database can then be connected using an authorized username and a password.
public static Connection getConnect(String username, String passwd)
    {
        // Set the driver class.
        String driver = "org.postgresql.Driver";
        // Database connection descriptor.
        String sourceURL = "jdbc:postgresql://10.10.0.13:8000/postgres";
        Connection conn = null;

        try
        {
            // Load the driver.
            Class.forName(driver);
        }
        catch( Exception e )
        {
            e.printStackTrace();
            return null;
        }

        try
        {
             // Establish a connection.
            conn = DriverManager.getConnection(sourceURL, username, passwd);
            System.out.println("Connection succeed!");
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }

        return conn;
    };
// The following code uses the Properties object as a parameter to establish a connection.
public static Connection getConnectUseProp(String username, String passwd)
    {
        // Set the driver class.
        String driver = "org.postgresql.Driver";
        // Database connection descriptor.
        String sourceURL = "jdbc:postgresql://10.10.0.13:8000/postgres?";
        Connection conn = null;
        Properties info = new Properties();

        try
        {
            // Load the driver.
            Class.forName(driver);
        }
        catch( Exception e )
        {
            e.printStackTrace();
            return null;
        }

        try
        {
             info.setProperty("user", username);
             info.setProperty("password", passwd);
             // Establish a connection.
             conn = DriverManager.getConnection(sourceURL, info);
             System.out.println("Connection succeed!");
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }

        return conn;
    };