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
- Setting up the Python environment for IBM® Database servers.
- Issue the
import ibm_db
command from your Python script.
Procedure
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 https://github.com/ibmdb/python-ibmdb/wiki/APIs.
Example
- 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 ibm_db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username; 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 run SQL statements. The next step is to prepare and run SQL
statements.