All Products
Search
Document Center

AnalyticDB:Write data by using the Client SDK

Last Updated:Jan 27, 2026

The AnalyticDB for PostgreSQL Client software development kit (SDK) provides a high-performance method to copy data to AnalyticDB for PostgreSQL using APIs.

You can use the AnalyticDB for PostgreSQL Client SDK to develop custom programs to write data. The SDK simplifies the process of writing data to AnalyticDB for PostgreSQL. You do not need to manage connection pools or caches. Internal mechanisms, such as parallel processing, provide a significant performance increase compared to direct COPY or INSERT write operations.

Note

The primary function of the AnalyticDB for PostgreSQL Client SDK is to efficiently write the data that you provide. The SDK does not read or process raw data.

Maven repositories

You can use Maven to manage and configure the SDK version. The following is the Maven configuration:

<dependency>
  <groupId>com.alibaba.cloud.analyticdb</groupId>
  <artifactId>adb4pgclient</artifactId>
  <version>1.0.16</version>
</dependency>
Note

You can download the offline JAR packages from the following links: adb4pgclient-1.0.16.jar and adb4pgclient-1.0.16-jar-with-dependencies.jar.

Methods

Table 1. DatabaseConfig class

API Name

Description

setHost(String adbHost)

The connection address of the AnalyticDB for PostgreSQL instance to connect to.

setPort(int port)

The port of the AnalyticDB for PostgreSQL instance. The default value is 5432.

setDatabase(String database)

The name of the AnalyticDB for PostgreSQL database to connect to.

setUser(String username)

The username for the AnalyticDB for PostgreSQL database connection.

setPassword(String pwd)

The password for the AnalyticDB for PostgreSQL database connection.

addTable(List<String> table, String schema)

A list of tables to write to. Add tables separately based on their schema. You can call this method multiple times. This method no longer takes effect after you use the DatabaseConfig object to construct an Adb4PGClient object.

setColumns(List<String> columns, String tableName, String schemaName)

The columns of the table to insert data into. To insert data into all columns, use columnList.add("*"). You must set the columns for all tables in the table list. Otherwise, the check fails.

setInsertIgnore(boolean insertIgnore)

Specifies whether to ignore data rows that cause primary key conflicts. This setting applies to all configured tables. The default value is false, which means conflicting rows are overwritten.

setEmptyAsNull(boolean emptyAsNull)

Specifies whether to set empty data to null. This setting applies to all configured tables. The default value is false.

setParallelNumber(int parallelNumber)

The number of concurrent threads for writing data to AnalyticDB for PostgreSQL. This setting applies to all configured tables. The default value is 4. We do not recommend changing this value in most cases.

setLogger(Logger logger)

The logger object used in the client. Use slf4j.Logger.

setRetryTimes(int retryTimes)

The number of retries when an exception occurs during a commit to AnalyticDB for PostgreSQL. The default value is 3.

setRetryIntervalTime(long retryIntervalTime)

The retry interval. The unit is milliseconds (ms). The default value is 1000 ms.

setCommitSize(long commitSize)

The data volume in bytes for an autocommit. The default value is 10 MB. We do not recommend changing this setting.

setEnablePreHash(boolean enablePreHash)

If the destination table uses Beam storage and a deadlock occurs during the write process, enable this switch to improve write performance.

setMetaDataSchedulerInterval(int metaDataSchedulerInterval)

Adjusts the metadata update interval for the write table in the AnalyticDB for PostgreSQL Client SDK. The default value is 1 minute. The unit is minutes (min).

Table 2. Row class

API Name

Description

setColumn(int index, Object value)

Sets the value of a column. You must set the columns in order. With this method, Row instances cannot be reused. Each data record must have a separate Row instance.

setColumnValues(List<Object> values)

Writes a data row in List format directly into the Row.

updateColumn(int index, Object value)

Updates the value of a column. With this method, Row instances can be reused. Simply update the data in the Row instance.

Table 3. Adb4pgClient class

API Name

Description

addRow(Row row, String tableName, String schemaName) / addRows(List<Row> rows, String tableName, String schemaName)

Inserts a data record in row format. The data is stored in the SDK buffer and waits to be committed. If the data volume exceeds the `commitSize` value, an autocommit is triggered during the `addRow` or `addRows` call before the new data is added. If the autocommit fails, you must handle the exception, which contains a list of the failed data records.

addMap(Map<String, String> dataMap,String tableName, String schemaName) / addMaps(List<Map<String, String>> dataMaps, String tableName, String schemaName)

Inserts a data record in map format. This method is similar to `addRow`. If the buffer is full, an autocommit is triggered during the `addMap` or `addMaps` call before the new data is added. If the autocommit fails, you must handle the exception, which contains a list of the failed data records.

commit()

Commits the cached data to AnalyticDB for PostgreSQL. If the commit fails, an exception that contains the failed statements is thrown. You must handle this exception.

TableInfo getTableInfo(String tableName, String schemaName)

Retrieves the structure information of the specified table.

List<ColumnInfo> getColumnInfo(String tableName, String schemaName)

Retrieves the list of columns for the specified table. The columns are returned as `ColumnInfo` objects. You can use the columnInfo.isNullable() method to check whether a column can be null.

stop()

After you finish using the instance, call the `stop` method to release internal thread pools and resources. If uncommitted data exists in the memory, an exception is thrown. To force a stop, use the forceStop() method.

forceStop()

Forcibly releases internal thread pools and resources. Any uncommitted data cached in the memory is lost. This method is not recommended for general use.

Connection getConnection() throws SQLException

Retrieves a database `Connection` object from the client connection pool. You can use the retrieved `Connection` object for operations other than COPY. This object is used in the same way as a standard Java Database Connectivity (JDBC) connection.

Note

After you finish using the connection, you must release the corresponding resources, such as `ResultSet`, `Statement`, and `Connection` objects.

Table 4. ColumnInfo class

API Name

Description

boolean isNullable()

Checks if the column can be null.

Error code

Error code

Description

COMMIT_ERROR_DATA_LIST

101

An exception occurred for some data during the commit. The failed data is returned.

Note

Use e.getErrData() to get the list of failed data (List<String>). This error code can occur during addMap(s), addRow(s), and commit operations. You must handle the exception for this error code separately for these operations.

COMMIT_ERROR_OTHER

102

Other exceptions occurred during the commit.

ADD_DATA_ERROR

103

An exception occurred while adding data.

CREATE_CONNECTION_ERROR

104

An exception occurred while creating a connection.

CLOSE_CONNECTION_ERROR

105

An exception occurred while closing a connection.

CONFIG_ERROR

106

A configuration error occurred in DatabaseConfig.

STOP_ERROR

107

An error occurred while stopping the instance.

OTHER

999

The default exception error code.

Code example

public class Adb4pgClientUsage {
    public void demo() {
        DatabaseConfig databaseConfig = new DatabaseConfig();
        // Should set your database real host or url
        databaseConfig.setHost("100.100.100.100");
        // Should set your database real port
        databaseConfig.setPort(8888);
        // The username for the database connection.
        databaseConfig.setUser("your user name");
        // The password for the database connection.
        databaseConfig.setPassword("your password");
      // The database to connect to.
        databaseConfig.setDatabase("your database name");
        // Set the list of tables to write to.
        List<String> tables = new ArrayList<String>();
        tables.add("your table name 1");
        tables.add("your table name 2");

        // You can call addTable separately for tables in different schemas. However, after a Client instance is created from the DatabaseConfig, the table configuration cannot be changed. /
        // If you pass null for the schema, the default schema 'public' is used.
        databaseConfig.addTable(tables, "table schema name");

        // Set the columns of the table to write to.
        List<String> columns = new ArrayList<String>();
        columns.add("column1");
        columns.add("column2");
        // To write to all columns, use columns.add("*").
        databaseConfig.setColumns(columns, "your table name 1", "table schema name");
        databaseConfig.setColumns(Collections.singletonList("*"),"your table name 2", "table schema name");


        // If the value of column is empty, set null
        databaseConfig.setEmptyAsNull(false);
        // Use the 'insert ignore' method for insertion.
        databaseConfig.setInsertIgnore(true);
        // Retry three times if an exception occurs when writing to the database during a commit.
        databaseConfig.setRetryTimes(3);
        // The retry interval is 1s. The unit is ms.
        databaseConfig.setRetryIntervalTime(1000);
        // Initialize AdbClient. After the instance is initialized, the DatabaseConfig settings cannot be changed.
        Adb4pgClient adbClient = new Adb4pgClient(databaseConfig);

        // Batch the data. Add multiple times, then commit. For details on batch size, see the "Notes" section.
        for (int i = 0; i < 10; i++) {
            // Add row(s) to buffer. One instance for one record
            Row row = new Row(columns.size());
            // Set column
            // the column index must be same as the sequence of columns
            // the column value can be any type, internally it will be formatted according to column type
            row.setColumn(0, i); // Number value
            row.setColumn(1, "string value"); // String value
            // If the buffer is full, an autocommit is triggered during an addRow or addMap call.
            // If the commit fails, an AdbClientException is returned with the error code COMMIT_ERROR_DATA_LIST.
            adbClient.addRow(row, "your table name 1", "table schema name");
        }

        Row row = new Row();
        row.setColumn(0, 10); // Number value
        row.setColumn(1, "2018-01-01 08:00:00"); // Date/Timestamp/Time value
        adbClient.addRow(row, "your table name 1", "table schema name");
        // Update a column. The Row instance can be reused.
        row.updateColumn(0, 11);
        row.updateColumn(1, "2018-01-02 08:00:00");
        adbClient.addRow(row, "your table name 1", "table schema name");

        // Add map(s) to buffer
        Map<String, String> rowMap = new HashMap<String, String>();
        rowMap.put("t1", "12");
        rowMap.put("t2", "string value");
        // Batching is required here. We recommend committing after multiple add calls.
        adbClient.addMap(rowMap, "your table name 2", "table schema name");

        // Commit buffer to ADS
        // Buffer is cleaned after successfully commit to ADS
        try {
            adbClient.commit();
        } catch (Exception e) {
            // TODO: Handle exception here
        } finally {
            adbClient.stop();
        }
    }

}

Notes

  • The AnalyticDB for PostgreSQL Client SDK is not thread-safe. In a multi-threaded environment, each thread must maintain its own `Client` object.

    Important

    We do not recommend sharing an SDK instance among multiple threads. In addition to thread safety issues, a shared client can easily become a write performance bottleneck.

  • Data is considered successfully written to AnalyticDB for PostgreSQL only after the `commit` call succeeds.

  • When the client throws an exception, you must decide how to handle it based on the error code. If a data writing error occurs, you can resubmit the data, or log the problematic data and then skip it.

  • Using more write threads does not always result in better performance. Because applications often batch data, memory consumption can be high. Therefore, you must closely monitor the application's garbage collection (GC) status.

  • Do not use a batch size that is too small. Otherwise, the benefits of batch writing are lost. If possible, we recommend adding at least 10,000 records before you commit the data.

  • You must set all `DatabaseConfig` configuration items before the client object is initialized. These settings cannot be changed after the client object is instantiated.

  • The Client SDK is designed to optimize write (INSERT) performance. For other SQL operations, retrieve a JDBC connection using the getConnection() method and handle the operations through standard JDBC interfaces.