To connect to a DB2 database
using COBOL, do the following:
- Create a local COBOL project in Rational® Developer for System z®.
- Link the DB2 library
to your project by opening the Local Link Optionsproperty
page.
- Type /de db2api.lib in the Link
Options field.
- Click Local COBOL Build Options and
provide the following information:
- SYSLIB
installation_directory\INCLUDE\COBOL_A
Note: Replace installation_directory with
your DB2 installation directory.
- Select Source contains embedded SQL.
- Click Browse and select your DB2 connection.
- Optional: Enter additional options to pass
onto the SQL preprocessor in the Other SQL options field. Separate multiple SQL options with commas.
- Click OK.
Note: Do not
specify DB2-related options in the Compiler Options field.
The necessary compiler options and sub-options will automatically
be generated for you from your selected DB2 connection
and the options you enter in the Other SQL options field.
- Insert the following statement before using any SQL statements
in the WORKING-STORAGE, LOCAL-STORAGE,
or LINKAGE sections of your code:
EXEC SQL INCLUDE SQLCA END-EXEC;
- Delimit SQL statements with EXEC SQL and END-EXEC statements.
Here is an example using the DB2 Sample
database:
EXEC SQL UPDATE employee
SET firstnme = 'Myname'
WHERE empno = '000010' END-EXEC.
- Sample COBOL code to access a DB2 database
* ---------------------------------------------------
* Module Name: COBOLDB2.cbl
*
* Description: Sample COBOL with DB2 program.
*
* Purpose: Performs a Select on the employee table
* in the Sample database shipped with DB2.
*
* COMPLILER OPTIONS (be sure to change the USERNAME and PASSWORD):
* DATA,EXIT(ADEXIT(FTTDBKW)),sql('database sample user USERNAME using PASSWORD')
*
* SYSLIB:
* C:\Program Files\IBM\SQLLIB\INCLUDE\COBOL_A
*
* ILINK OPTIONS:
* /de db2api.lib
*
* ---------------------------------------------------
Identification Division.
Program-ID. COBOLDB2.
Data Division.
*Make sure you have SQLCA included in Working-Storage
Working-Storage Section.
EXEC SQL INCLUDE SQLCA END-EXEC.
*Data structure to store the Firstname of the employee
01 Program-pass-fields.
05 Firstnme Pic x(30).
Procedure Division.
*A Connection to the database must be made!
EXEC SQL CONNECT TO sample END-EXEC.
*Performs a SQL SELECT to get the firstname of the employee
*with the employee number of 10.
EXEC SQL SELECT firstnme INTO :Firstnme
FROM employee
WHERE empno = '000010' END-EXEC.
*Displays the firstname we pulled from the Sample database.
Display "Firstname"
Display "========="
Display Firstnme
Display " "
*Displays the status of the SQL statements
Display SQLCA
Goback.