DB2 10.5 for Linux, UNIX, and Windows

Connecting to an IBM database server in Python

Before you can run SQL statements to create, update, delete, or retrieve data, you must connect to a database. You can use the ibm_db API to connect to a database through either a cataloged or uncataloged connection. To improve performance, you can also create a persistent connection.

Before you begin


Call one of the listed functions to establish connection to an IBM database server:
Table 1. ibm_db connection functions
Function Description
ibm_db.connect Creates a nonpersistent connection.
ibm_db.pconnect Creates a persistent connection. A persistent connection remains open after the initial Python script request, which allows subsequent Python requests to reuse the connection. The subsequent Python connect requests must have an identical set of credentials.

The database value that you pass as an argument to these functions can be either a cataloged database name or a complete database connection string for a direct TCP/IP connection. You can specify optional arguments that control the timing of committing transactions, the case of the column names that are returned, and the cursor type.

If the connection attempt fails, you can retrieve diagnostic information by calling the ibm_db.conn_error or ibm_db.conn_errormsg function.

For more information about the ibm_db API, see http://code.google.com/p/ibm-db/wiki/APIs.


Example 1: Connect to a local or cataloged database

import ibm_db
conn = ibm_db.connect("database","username","password")

Example 2: Connect to an uncataloged database

import ibm_db
                PWD=password;", "", "")

What to do next

If the connection attempt is successful, you can use the connection resource when you call ibm_db functions that execute SQL statements. Next, you prepare and execute SQL statements.