Connect to a Db2 database

The JSON API uses JDBC connections to perform various database operations, such as connecting to a Db2 database.

To use the database you must get an instance of a DB object. This object can be initialized with a Connection JDBC connection, or DataSource, or the database URL, user name, and password.

The following snippet from a Java™ program demonstrates how to connect to a Db2 database:
 //Create a context and a dataSource 
 Context initialContext = new InitialContext(); 
 DataSource dataSource = (DataSource)initialContext.lookup("jdbc/myDB2");
 //The dataSource instance becomes a cache key for metadata for the target database 
 DB db = NoSQLClient.getDB(dataSource);
The following overloaded methods are available to get a DB instance:
  • NoSQLClient.getDB(java.sql.Connection)
    
  • NoSQLClient.getDB(javax.sql.DataSource)
    
  • NoSQLClient.getDB(String, String, String)
    The string arguments for the third instance of the getDB method take the following arguments:
    jdbcUrl
    Specifies a URL that can be used to connect with a JDBC connection.
    user
    Specifies a user name that can be used to connect the database.
    password
    Specifies a password.
Note: This DB instance must not be shared between threads. Each thread must make its own NoSQLClient.getDB() method call.
Table 1. Methods on DB to control transactional behavior
Method Description
public void startTransaction() Gets a connection if needed, and sets auto-commit to false. If a connection pool or data source is being used, it puts the DB in single connection mode until a future commitTransaction() or rollbackTransaction().
public void commitTransaction() Commits a transaction started by startTransaction().
public void rollbackTransaction() Rollback a transaction that was started by startTransaction().
public void setAutoCommit(boolean autoCommit) Sets auto-commit if the Db2 server is using single connection mode. It is an error to call this method in DataSource mode.
Note: The transaction APIs described in this table are not applicable for the fire and forget mode.

Obtain a single-mode connection when you are using the transaction APIs to avoid situations where starting a transaction forcibly changes the connection pool mode into single-mode.

Documents are not inserted if an error occurs. With these APIs, either all or none of the documents are inserted.