Python DB2 utilities
The db2util module The db2util module provides a few utilities that make it easier to work with the DB2 interface. The entire source code is provided below. The rest of this section highlights the most useful functions and show examples of thei r use
"""Utilities for use with DB2 and the Python DB2 interface.""" |
Connecting
The db2util
module provides a connect()
function that parallels the connect()
constructor in the DB2
module. The only difference is that the db2util
version provides keyword arguments with useful default values, which
can be quite helpful in a Python shell such as IDLE or PyCrust. Also,
since a connection is the entry point to all the other DB2
functionality, you have access to everything you need by simply
importing the db2util
module. Here is the code for the connect()
function:
def connect(dsn='sample', uid='db2inst1', pwd='ibmdb2', |
Using the db2util
connect()
function is almost identical to the DB2
module's version:
>>> from PyDB2 import db2util |
Fetching and printing
When running SELECT queries you often want to see the results presented in nicely formatted rows and columns. For this, the db2util
module provides the fp()
function, which stands for "fetch and print." This function requires a
cursor object that has already executed a SELECT query, but hasn't
fetched any rows yet. Optionally, you may supply a column separator and
a value to represent NULL values. The source code is quite short:
def fp(cursor, sep=' ', null=''): |
Here are the results of running fp()
with a few different queries:
>>> from PyDB2 import db2util |
Cursor printing
The fp()
function described in the previous section had very few lines of source
code because it relied heavily on the functionality provided by the cprint()
function. The cprint()
function also expects to receive a cursor object that has already
executed a SELECT query, but it also requires the rows returned by one
of the fetch methods. Like fp()
, you may supply a separator and NULL representation. Looking at the source code reveals the use of the cursor.description2
to determine the column formatting for the result set:
def cprint(cursor, rows, sep=' ', null=None): |
Here is one example of cprint()
where we supply a different column separator and NULL representation:
>>> curs.execute('SELECT * FROM STAFF WHERE YEARS > 9') |
Looking at the source code for cprint()
, you can see that it calls upon several other functions defined in the db2util
module. While we won't describe the rest of them in this tutorial,
their purpose is readily apparent and the code should be relatively
easy to follow. These functions illustrate the use of the DB2 module
and provide a solid foundation to build upon. For example, the db2util
module could be used in the creation of a graphical query tool.