DB2 Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
DB2 Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
IBM
Notices
This information was developed for products and services offered in the US. This material might be
available from IBM in other languages. However, you may be required to own a copy of the product or
product version in that language in order to access it.
IBM may not offer the products, services, or features discussed in this document in other countries.
Consult your local IBM representative for information on the products and services currently available in
your area. Any reference to an IBM product, program, or service is not intended to state or imply that only
that IBM product, program, or service may be used. Any functionally equivalent product, program, or
service that does not infringe any IBM intellectual property right may be used instead. However, it is the
user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service.
IBM may have patents or pending patent applications covering subject matter described in this
document. The furnishing of this document does not grant you any license to these patents. You can send
license inquiries, in writing, to:
For license inquiries regarding double-byte character set (DBCS) information, contact the IBM Intellectual
Property Department in your country or send inquiries, in writing, to:
Each copy or any portion of these sample programs or any derivative work must include a copyright
notice as follows:
© (your company name) (year).
Portions of this code are derived from IBM Corp. Sample Programs.
© Copyright IBM Corp. _enter the year or years_.
Trademarks
IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business
Machines Corp., registered in many jurisdictions worldwide. Other product and service names might be
trademarks of IBM or other companies. A current list of IBM trademarks is available on the web at
"Copyright and trademark information" at www.ibm.com/legal/copytrade.shtml.
Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the
United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other countries.
Java and all Java-based trademarks and logos are trademarks or registered trademarks of Oracle and/or
its affiliates.
ii Notices
Applicability
These terms and conditions are in addition to any terms of use for the IBM website.
Personal use
You may reproduce these publications for your personal, noncommercial use provided that all proprietary
notices are preserved. You may not distribute, display or make derivative work of these publications, or
any portion thereof, without the express consent of IBM.
Commercial use
You may reproduce, distribute and display these publications solely within your enterprise provided that
all proprietary notices are preserved. You may not make derivative works of these publications, or
reproduce, distribute or display these publications or any portion thereof outside your enterprise, without
the express consent of IBM.
Rights
Except as expressly granted in this permission, no other permissions, licenses or rights are granted, either
express or implied, to the publications or any information, data, software or other intellectual property
contained therein.
IBM reserves the right to withdraw the permissions granted herein whenever, in its discretion, the use of
the publications is detrimental to its interest or, as determined by IBM, the above instructions are not
being properly followed.
You may not download, export or re-export this information except in full compliance with all applicable
laws and regulations, including all United States export laws and regulations.
IBM MAKES NO GUARANTEE ABOUT THE CONTENT OF THESE PUBLICATIONS. THE PUBLICATIONS ARE
PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY, NON-
INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
Notices iii
iv IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Contents
Notices...................................................................................................................i
Trademarks...................................................................................................................................................ii
Terms and conditions for product documentation......................................................................................ii
Tables................................................................................................................. vii
v
Index.................................................................................................................. 65
vi
Tables
1. Resources for the node-ibm_db driver and required IBM data server products........................................ 1
vii
viii
Chapter 1. Developing Node.jsl Applications
Table 1. Resources for the node-ibm_db driver and required IBM data server products
Description URL
Latest information about the IBM node-ibm_db https://www.npmjs.org/package/ibm_db1
driver. The link does not point to an IBM site.
Sample code. The link does not point to an IBM https://github.com/ibmdb/node-ibm_db/1
site.
List of installation requirements for Db2 database http://www-01.ibm.com/support/
products. knowledgecenter/SSEPGG_10.5.0/
com.ibm.db2.luw.qb.server.doc/doc/
r0025127.html
List of installation requirements for theIBM http://www-01.ibm.com/support/
Informix® server. knowledgecenter/SSGU8G_11.50.0/
com.ibm.expr.doc/ids_in_004x.htm
IBM Data Server Driver Package software https://www.ibm.com/support/pages/node/
download site 387577
IBM node-ibm_db driver forum. The link does not https://groups.google.com/forum/#!forum/node-
point to an IBM site. ibm_db1
Reported issues. The link does not point to an IBM https://github.com/ibmdb/node-ibm_db/issues1
site.
1 Any references to non-IBM websites are provided for convenience only and do not in any manner serve as
an endorsement of those websites. The content available at those non-IBM websites is not part of any
materials relating to the IBM products described herein. Your use of any non-IBM website is at your own
risk.
Procedure
To install the node-ibm_db driver:
1. Set the IBM_DB_HOME environment variable to your IBM data server product installation directory by
issuing the following command:
export IBM_DB_HOME=DB2HOME
where DB2HOME is the directory where the IBM data server product is installed. In a IBM Data Server
Driver Package environment, DB2HOME is the directory in which the client package is installed. For
example, if the client package is installed in the /home/db2inst1/dsdriver directory, issue the
following command:
export IBM_DB_HOME=/home/db2inst1/dsdriver
What to do next
Before you run any Node.js application that connects to an IBM database server, you must ensure that the
node-ibm_db driver can access the CLI driver by sourcing the db2profile script. The script is in the IBM
data server product installation directory. To source the script, issue the following command:
source DB2HOME/db2profile
Procedure
To verify the node-ibm_db driver installation:
1. Create a sample Node.js application to test the connection to the sample database.
Copy the following sample code into a file and save the file as test1.js.
//test1.js
var ibmdb = require('ibm_db');
ibmdb.open("DRIVER={DB2};DATABASE=sample;HOSTNAME=<hostname>;
UID=<user_id>;PWD=<password>;PORT=<port>;
PROTOCOL=TCPIP", function (err,conn) {
if (err) return console.log(err);
console.log(data);
conn.close(function () {
console.log('done');
});
});
});
where:
• <hostname> is the fully qualified host name of your IBM database server.
2 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
• <user_id> and <password> are a valid user ID and password for connecting to the sample database.
• <port> is the listener port of the IBM database server.
2. Run the test1.js application by issuing the node test1.js command:
C:\Users\IBM_ADMIN>node test1.js
[ { ID: 10,
NAME: 'Sanders',
DEPT: 20,
JOB: 'Mgr ',
YEARS: 7,
SALARY: 98357.5,
COMM: 1.5537297e-317 } ]
done
where:
Examples
Example 1: Connect to a database on the local host (client and server are on the same workstation)
use DBI;
$DATABASE = 'dbname';
$USERID = 'username';
$PASSWORD = 'password';
$dbh->disconnect;
Example 2: Connect to a database on the remote host (client and server are on different workstations)
use DBI;
$dbh->disconnect;
Procedure
To fetch results:
1. Create a database handle by connecting to the database with the DBI->connect statement.
2. Create a statement handle from the database handle.
6 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
For example, you can return the statement handle $sth from the database handle by calling the
prepare method and passing an SQL statement as a string argument, as demonstrated in the Perl
statement example:
my $sth = $dbhandle->prepare(
'SELECT firstnme, lastname
FROM employee '
);
3. Issue the SQL statement by calling the execute method on the statement handle. A successful call to
the execute method associates a result set with the statement handle.
For example, you can run the statement prepared in the previous Perl statement by using the listed
example:
#Note: $rc represents the return code for the execute call
my $rc = $sth->execute();
4. Fetch a row from the result set associated with the statement handle by calling the fetchrow
method. The Perl DBI returns a row as an array with one value per column.
For example, you can return all of the rows from the statement handle in the previous example by
using the listed Perl statement:
Examples
The example shows how to connect to a database and issue a SELECT statement from an application
written in Perl.
#!/usr/bin/perl
use DBI;
my $database='dbi:DB2:sample';
my $user='';
my $password='';
my $sth = $dbh->prepare(
q{ SELECT firstnme, lastname
FROM employee }
)
or die "Can't prepare statement: $DBI::errstr";
my $rc = $sth->execute
or die "Can't execute statement: $DBI::errstr";
# check for problems that might have terminated the fetch early
warn $DBI::errstr if $DBI::err;
$sth->finish;
$dbh->disconnect;
my $sth = $dbhandle->prepare(
'SELECT firstnme, lastname
FROM employee
WHERE salary > ?'
);
my $rc = $sth->execute(25000);
·
·
·
my $rc = $sth->execute(35000);
Perl Restrictions
Some restrictions apply to the support that is available for application development in Perl.
The Perl DBI module supports only dynamic SQL. When you must execute a statement multiple times,
you can improve the performance of your Perl applications by issuing a prepare call to prepare the
statement.
For current information about the restrictions on a specific version of the DBD::DB2 driver installation, see
the CAVEATS file in the DBD::Db2 driver package.
8 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Examples
The example is a Perl program that uses pureXML:
#!/usr/bin/perl
use DBI;
use strict ;
my $database='dbi:Db2:sample';
my $user='';
my $password='';
my $datatype = "record" ;
# $datatype = "LOB" ;
# SQL SELECT statement returns home phone element from XML data
$stmt = qq(
SELECT XMLQUERY ('
\$d/*:customerinfo/*:phone[\@type = "home"] '
passing data as "d")
FROM xmlTest
) ;
# Drop table
$stmt = "DROP TABLE xmlTest" ;
$sth = $dbh->prepare($stmt);
$sth->execute();
$sth->finish;
$dbh->disconnect;
##############
sub printRecord {
print "output data as record\n" ;
my $offset = 0;
my $buff="";
$sth->fetch();
while( $buff = $sth->blob_read(1,$offset,1000000)) {
print $buff;
$offset+=length($buff);
$buff="";
}
warn $DBI::errstr if $DBI::err;
}
sub insertData {
my $catID = 1011 ;
my $rc = $sth->execute
or die "Can't execute statement: $DBI::errstr";
Before running the Perl sample programs, you must install the latest DBD::DB2 driver for Perl DBI. For
information about how to obtain the latest driver, see http://search.cpan.org/~ibmtordb2/.
The Perl sample programs for Db2 database are available in the sqllib/samples/perl directory.
Procedure
To run a Perl sample program through the Perl interpreter:
• Enter the interpreter name and the program name (including the file extension):
• If connecting locally on the server:
10 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
perl dbauth.pl
Some of the sample programs require you to run support files. For example, the tbsel sample
program requires several tables that are created by the tbselcreate.db2 CLP script. The
tbselinit script (UNIX), or the tbselinit.bat batch file (Windows), first calls tbseldrop.db2 to
drop the tables if they exist, and then calls tbselcreate.db2 to create them. Therefore, to run the
tbsel sample program, issue the listed commands:
• If connecting locally on the server:
tbselinit
perl tbsel.pl
tbselinit
perl tbsel.pl sample <userid> <password>
Note: For a remote client, you must modify the connect statement in the tbselinit or
tbselinit.bat file to hardcode your user ID and password: db2 connect to sample user
<userid> using <password>
To build a host language routine, you must have the appropriate compiler set up on the server. SQL
procedures do not require a compiler. The shared library can be built on the server only, and not from a
remote client.
Procedure
To create SQL procedures in a shared library and then accesses the procedures from a Perl application:
1. Create and catalog the SQL procedures in the library. For example, go to the samples/sqlpl
directory on the server, and run the listed commands to create and catalog the SQL procedures in the
spserver library:
2. Go back to the perl samples directory (this can be on a remote client workstation), and run the Perl
interpreter on the client program to access the spserver shared library:
• If connecting locally on the server:
perl spclient
1. Includes the Windows binary files. Most Linux distributions come with PHP already precompiled.
Setting up the PHP environment for IBM Data Server products on Windows
Before you can connect to an IBM database server and run SQL statements, you must set up the PHP
environment.
You must have the following required software installed on your system:
• PHP version 5 or later
• If your PHP application will connect to a remote IBM database, one of the following products on the
computer where your application will run:
– The IBM Data Server Client product
– The IBM Data Server Runtime Client product
– The IBM Data Server Driver Package product
– The IBM Data Server Driver for ODBC and CLI product
If your PHP application connects to an IBM database server on the local computer, no additional IBM
data server products are required.
Procedure
To install the ibm_db2 and pdo_ibm php extensions:
1. Copy the ibm_db2 and pdo_ibm extension files into the \ext\ subdirectory of your PHP installation
directory.
The ibm_db2 and pdo_ibm extension files can be obtained from the following sources:
• IBM Data Server product installation path
• PHP Extension Community Library (PECL)
– For the ibm_db2 extension file, see http://windows.php.net/downloads/pecl/releases/ibm_db2/
– For the pdo_ibm extension file, see http://windows.php.net/downloads/pecl/releases/pdo_ibm/
14 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Note: If you installed the IBM Data Server Driver for ODBC and CLI software, you must obtain the
ibm_db2 and pdo_ibm extension files separately from the PHP Extension Community Library (PECL).
• If you have thread safe PHP environment, copy the following extension files from the IBM Data
Server product installation path into the \ext\ subdirectory of your PHP installation directory:
– php_ibm_db2_X_X_XXX_ts.dll
– php_pdo_ibm_X_X_XXX_ts.dll
• If you have non-thread safe PHP environment, copy the following extension files from the IBM Data
Server product installation path into the \ext\ subdirectory of your PHP installation directory:
– php_ibm_db2_X_X_XXX_nts.dll
– php_pdo_ibm_X_X_XXX_nts.dll
2. Open the php.ini file in an editor of your choice. Edit the extension entry in the php.ini file in the
PHP installation directory to reference the PHP driver.
• For the thread safe PHP environment:
extension=php_pdo.dll
extension=php_ibm_db2_X_X_XXX_ts.dll
extension=php_pdo_ibm_X_X_XXX_ts.dll
extension=php_pdo.dll
extension=php_ibm_db2_X_X_XXX_nts.dll
extension=php_pdo_ibm_X_X_XXX_nts.dll
3. If the PHP application that is connecting to an IBM database server is running in the HTTP server
environment, restart the HTTP Server so the new configuration settings take effect.
Setting up the PHP environment for IBM Data Server products on Linux or UNIX
Before you can connect to an IBM database server and run SQL statements, you must set up the PHP
environment.
You must have the following required software installed on your system:
• PHP version 5 or later
• If your PHP application connects to a remote IBM database, the computer that runs your PHP
application requires one of the following products:
– The IBM Data Server Client product
– The IBM Data Server Runtime Client product
– The IBM Data Server Driver Package product
– The IBM Data Server Driver for ODBC and CLI product
If your PHP application connects to an IBM database server on the local computer, no additional IBM
data server products are required.
Procedure
To install the ibm_db2 and pdo_ibm php extensions:
1. Using the export command, set the environment variable IBM_DB_HOME.
$export IBM_DB_HOME=DB2HOME
The DB2HOME is the directory where the IBM Data Server product is installed. For example:
$ export IBM_DB_HOME=/home/db2inst1/sqllib
$ phpize --clean
$ phpize
$ ./configure
$ make
$ make install
c. If you are installing the pdo_ibm extension, you must run the following configure command:
$./configure --with-PDO_IBM=DB2HOME
The DB2HOME variable is the directory where the IBM Data Server product is installed.
• Use the compiled extensions included with the IBM Data Server products:
a. You must determine whether your PHP environment is threadsafe or not threadsafe by issuing
the following command:
b. The IBM data server client and IBM Data Server Driver Package software are shipped with two
types of PHP drivers:
– Threadsafe: ibm_db2_XX_ts.so and pdo_ibm_XX_ts.so
– Not threadsafe: ibm_db2_XX_nts.so and pdo_ibm_XX_nts.so
Using the cp command, copy the appropriate PHP driver share library files to the installed PHP
extension directory as ibm_db2.so and pdo_ibm.so files.
For a 32-bit PHP driver:
$ cp DB2HOME/php/php32/ibm_db2_XX_[ts/nts].so <local_php_directory>/php/lib/php/extensions/ibm_db2.so
$ cp DB2HOME/php/php32/pdo_ibm_XX_[ts/nts].so <local_php_directory>/php/lib/php/extensions/pdo_ibm.so
The DB2HOME variable is the directory where the IBM Data Server product is installed.
3. Open the php.ini file in an editor of your choice. Edit the extension entry in the php.ini file in the
<local_php_directory>/php/lib directory to reference the PHP driver:
extension=pdo.so
extension=ibm_db2.so
extension=pdo_ibm.so
4. Ensure that the PHP driver can access the libdb2.so CLI driver file by setting the LD_LIBRARY_PATH
variable for Linux and UNIX operating systems other than the AIX operating system. For AIX operating
system, you must set LIBPATH variable.
16 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
• For a 32-bit Linux and UNIX operating systems other than the AIX operating system, use the export
command to set the IBM_DB_HOME/lib32 directory to the LD_LIBRARY_PATH variable.
export LD_LIBRARY_PATH=DB2HOME/lib32
• For a 32-bit AIX operating system, use the export command to set the IBM_DB_HOME/lib32
directory to the: LIBPATH variable.
export LIBPATH=DB2HOME/lib32
• For a 64-bit Linux and UNIX operating systems other than the AIX operating system, use the export
command to set the LD_LIBRARY_PATH variable to the IBM_DB_HOME/lib64 directory.
export LD_LIBRARY_PATH=DB2HOME/lib64
• For a 64-bit AIX operating system, use the export command to set the LD_LIBRARY_PATH variable
to the IBM_DB_HOME/lib64 directory.
export LIBPATH=DB2HOME/lib64
5. Optional: If the PHP application that is connecting to an IBM database server is running in the HTTP
server environment:
a) Add the LD_LIBRARY_PATH variable in the httpd.conf file.
For a 32-bit architecture, set LD_LIBRARY_PATH to the DB2HOME\lib32 directory. For a 64-bit
architecture set LD_LIBRARY_PATH to the DB2HOME\lib64 directory.
b) Restart the HTTP server so the new configuration settings take effect.
Before connecting to an IBM data server database through the ibm_db2 extension, you must set up the
PHP environment on your system and enable the ibm_db2 extension.
Procedure
To return a connection resource that you can use to call SQL statements, call one of the listed connection
functions:
Example
Connect to a cataloged database.
<?php
$database = "sample";
$user = "db2inst1";
$password = "";
if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>
What to do next
If the connection attempt is successful, you can use the connection resource when you call ibm_db2
functions that execute SQL statements. Next, prepare and execute SQL statements.
Examples
Enable trusted contexts, switch users, and get the current user ID.
<?php
$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";
$tc_user = "tcuser";
$tc_pass = "tcpassword";
18 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);
if(db2_get_option($tc_conn, "trustedcontext")) {
$userBefore = db2_get_option($tc_conn, "trusted_user");
if($userBefore != $userAfter) {
echo "User has been switched." . "\n";
}
}
db2_close($tc_conn);
}
else {
echo "Explicit Trusted Connection failed.\n";
}
?>
Procedure
To prepare and execute a single SQL statement, call the db2_exec function, passing the listed
arguments:
connection
A valid database connection resource returned from the db2_connect or db2_pconnect function.
statement
A string that contains the SQL statement. This string can include an XQuery expression that is called
by the XMLQUERY function.
options
Optional: An associative array that specifies statement options:
DB2_ATTR_CASE
For compatibility with database systems that do not follow the SQL standard, this option sets the
case in which column names will be returned to the application. By default, the case is set to
DB2_CASE_NATURAL, which returns column names as they are returned by the database. You
Example
Example 1: Executing a single SQL statement.
<?php
$conn = db2_connect("sample", "db2inst1", "");
$sql = "SELECT * FROM DEPT";
$stmt = db2_exec($conn, $sql);
db2_close($conn);
?>
<?php
$xquery = '$doc/customerinfo/phone';
$stmt = db2_exec($conn, "select xmlquery('$xquery'
PASSING INFO AS \"doc\") from customer");?>
What to do next
If the SQL statement selected rows using a scrollable cursor, or inserted, updated, or deleted rows, you
can call the db2_num_rows function to return the number of rows that the statement returned or
affected. If the SQL statement returned a result set, you can begin fetching rows.
Preparing and executing SQL statements with variable input in PHP (ibm_db2)
To prepare and execute an SQL statement that includes variable input, use the db2_prepare,
db2_bind_param, and db2_execute functions. Preparing a statement improves performance because
the database server creates an optimized access plan for data retrieval that it can reuse if the statement
is executed again.
Procedure
To prepare and execute an SQL statement that includes parameter markers:
1. Call the db2_prepare function, passing the listed arguments:
connection
A valid database connection resource returned from the db2_connect or db2_pconnect
function.
20 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
statement
A string that contains the SQL statement, including question marks (?) as parameter markers for
any column or predicate values that require variable input. This string can include an XQuery
expression that is called the XMLQUERY function. You can only use parameter markers as a place
holder for column or predicate values. The SQL compiler is unable to create an access plan for a
statement that uses parameter markers in place of column names, table names, or other SQL
identifiers.
options
Optional: An associative array that specifies statement options:
DB2_ATTR_CASE
For compatibility with database systems that do not follow the SQL standard, this option sets
the case in which column names will be returned to the application. By default, the case is set
to DB2_CASE_NATURAL, which returns column names as they are returned by the database.
You can set this parameter to DB2_CASE_LOWER to force column names to lowercase, or to
DB2_CASE_UPPER to force column names to upper case.
DB2_ATTR_CURSOR
This option sets the type of cursor that ibm_db2 returns for result sets. By default, ibm_db2
returns a forward-only cursor (DB2_FORWARD_ONLY) which returns the next row in a result
set for every call to db2_fetch_array, db2_fetch_assoc, db2_fetch_both,
db2_fetch_object, or db2_fetch_row. You can set this parameter to DB2_SCROLLABLE to
request a scrollable cursor so that the ibm_db2 fetch functions accept a second argument
specifying the absolute position of the row that you want to access within the result set.
If the function call succeeds, it returns a statement handle resource that you can use in subsequent
function calls that are related to this query.
If the function call fails (returns False), you can use the db2_stmt_error or db2_stmt_errormsg
function to retrieve diagnostic information about the error.
2. Optional: For each parameter marker in the SQL string, call the db2_bind_param function, passing
the listed arguments. Binding input values to parameter markers ensures that each input value is
treated as a single parameter, which prevents SQL injection attacks against your application.
stmt
A prepared statement returned by the call to the db2_prepare function.
parameter-number
An integer that represents the position of the parameter marker in the SQL statement.
variable-name
A string that specifies the name of the PHP variable to bind to the parameter specified by
parameter-number.
3. Call the db2_execute function, passing the listed arguments:
stmt
A prepared statement returned by the db2_prepare function.
parameters
Optional: An array that contains the values to use in place of the parameter markers, in order.
For more information about the ibm_db2 API, see http://www.php.net/docs.php.
Example
Prepare and execute a statement that includes variable input.
$sql = "SELECT firstnme, lastname FROM employee WHERE bonus > ? AND bonus < ?";
$stmt = db2_prepare($conn, $sql);
if (!$stmt) {
// Handle errors
}
db2_execute($stmt);
// Process results
What to do next
If the SQL statement returns one or more result sets, you can begin fetching rows from the statement
resource.
Obtain a connection resource by calling one of the connection functions in the ibm_db2 API.
Procedure
To insert a large object into the database directly from a file:
1. Call the db2_prepare function to prepare an INSERT statement with a parameter marker that
represents the large object column.
2. Set the value of a PHP variable to the path and name of the file that contains the data for the large
object. The path can be relative or absolute, and is subject to the access permissions of the PHP
executable file.
3. Call the db2_bind_param function to bind the parameter marker to the variable. The third argument
to this function is a string representing the name of the PHP variable that holds the path and name of
the file. The fourth argument is DB2_PARAM_FILE, which tells the ibm_db2 extension to retrieve the
data from a file.
4. Call the db2_execute function to issue the INSERT statement.
Example
Insert a large object into the database.
$picture = "/opt/albums/spook/grooming.jpg";
$rc = db2_bind_param($stmt, 1, "picture", DB2_PARAM_FILE);
$rc = db2_execute($stmt);
You must have a statement resource returned by either the db2_exec or db2_execute function that
has one or more associated result sets.
22 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Procedure
To fetch data from a result set:
1. Fetch data from a result set by calling one of the fetch functions.
Example
Example 1: Fetch rows from a result set by calling the db2_fetch_object function
<?php
$conn = db2_connect("sample", "db2inst1", "password");
$sql = 'SELECT FIRSTNME, LASTNAME FROM EMPLOYEE WHERE EMPNO = ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array('000010'));
while ($row = db2_fetch_object($stmt)) {
print "Name:
";
}
db2_close($conn);
?>
Example 2: Fetch rows from a result set by calling the db2_fetch_row function
<?php
$conn = db2_connect("sample", "db2inst1", "password");
$sql = 'SELECT FIRSTNME, LASTNAME FROM EMPLOYEE WHERE EMPNO = ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array('000010'));
while (db2_fetch_row($stmt)) {
$fname = db2_result($stmt, 0);
$lname = db2_result($stmt, 'LASTNAME');
print "
Name: $fname $lname
";
}
db2_close($conn);
?>
Example 3: Fetch rows from a result set by calling the db2_fetch_both function
<?php
$conn = db2_connect("sample", "db2inst1", "password");
$sql = 'SELECT FIRSTNME, LASTNAME FROM EMPLOYEE WHERE EMPNO = ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array('000010'));
while ($row = db2_fetch_both($stmt)) {
print "
NAME: $row[0] $row[1]
";
print "
NAME: " . $row['FIRSTNME'] . " " . $row['LASTNAME'] . "
";
}
db2_close($conn);
?>
What to do next
When you are ready to close the connection to the database, call the db2_close function. If you attempt
to close a persistent connection that you created by using db2_pconnect, the close request returns
TRUE, and the IBM data server client connection remains available for the next caller.
Obtain a connection resource by calling one of the connection functions in the ibm_db2 API.
Procedure
To fetch a large object from the database directly into a file:
1. Create a PHP variable representing a stream. For example, assign the return value from a call to the
fopen function to a variable.
2. Create a SELECT statement by calling the db2_prepare function.
3. Bind the output column for the large object to the PHP variable representing the stream by calling the
db2_bind_param function. The third argument to this function is a string representing the name of
24 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
the PHP variable that holds the path and name of the file. The fourth argument is DB2_PARAM_FILE,
which tells the ibm_db2 extension to write the data into a file.
4. Issue the SQL statement by calling the db2_execute function.
5. Retrieve the next row in the result set by calling an ibm_db2 fetch function (for example,
db2_fetch_object).
For more information about the ibm_db2 API, see http://www.php.net/docs.php.
Example
Fetch a large object from the database.
Procedure
To call a stored procedure:
1. Call the db2_prepare function, passing the listed arguments:
connection
A valid database connection resource returned from db2_connect or db2_pconnect.
statement
A string that contains the SQL CALL statement, including parameter markers (?) for any input or
output parameters
options
Optional: A associative array that specifies the type of cursor to return for result sets. You can use
this parameter to request a scrollable cursor on database servers that support this type of cursor.
By default, a forward-only cursor is returned.
2. For each parameter marker in the CALL statement, call the db2_bind_param function, passing the
listed arguments:
stmt
The prepared statement returned by the call to the db2_prepare function.
parameter-number
An integer that represents the position of the parameter marker in the SQL statement.
variable-name
The name of the PHP variable to bind to the parameter specified by parameter-number.
parameter-type
A constant that specifies whether to bind the PHP variable to the SQL parameter as an input
parameter (DB2_PARAM_IN), an output parameter (DB2_PARAM_OUT), or a parameter that
accepts input and returns output (DB2_PARAM_INOUT).
This step binds each parameter marker to the name of a PHP variable that will hold the output.
3. Call the db2_execute function, passing the prepared statement as an argument.
Example
Prepare and execute an SQL CALL statement.
db2_execute($stmt);
What to do next
If the procedure call returns one or more result sets, you can begin fetching rows from the statement
resource.
You must have a statement resource returned by the db2_exec or db2_execute function that has
multiple result sets.
Procedure
To retrieve multiple result sets:
1. Fetch rows from the first result set returned from the procedure by calling one of the ibm_db2 fetch
functions, passing the statement resource as an argument. (The first result set that is returned from
the procedure is associated with the statement resource.)
26 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Table 6. ibm_db2 fetch functions (continued)
Function Description
Sets the result set. Use this function to
pointer to the next rowiterate through a result
or requested rowset.
Returns an object with. The properties of the
properties representingobject map to the names
columns in the fetchedof the columns in the
rowresult set.
2. Retrieve the subsequent result sets by passing the original statement resource as the first argument to
the db2_next_result function. You can fetch rows from the statement resource until no more rows
are available in the result set.
The db2_next_result function returns False when no more result sets are available or if the
procedure did not return a result set.
For more information about the ibm_db2 API, see http://www.php.net/docs.php.
Example
Retrieve multiple result sets from a stored procedure.
What to do next
When you are ready to close the connection to the database, call the db2_close function. If you attempt
to close a persistent connection that you created by using db2_pconnect, the close request returns
TRUE, and the persistent IBM data server client connection remains available for the next caller.
Examples
End the transaction when db2_commit or db2_rollback is called.
Connection errors
Use one of the listed functions to retrieve diagnostic information if a connection attempt fails.
28 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
SQL errors
Use one of the listed functions to retrieve diagnostic information if an attempt to prepare or execute an
SQL statement or to fetch a result from a result set fails.
switch($this->state):
case '22001':
// More data than allowed for the defined column
$message = "You entered too many characters for this value.";
break;
Examples
Example 1: Handle connection errors
Example 3: Handle SQL errors that result from executing prepared statements
Most of the ibm_db2 database metadata retrieval functions return result sets with columns defined for
each function. To retrieve rows from the result sets, use the ibm_db2 functions that are available for this
purpose.
The db2_client_info and db2_server_info functions directly return a single object with read-only
properties. You can use the properties of these objects to create an application that behaves differently
depending on the database management system to which it connects. For example, rather than encoding
a limit of the lowest common denominator for all possible database management systems, a Web-based
database administration application built on the ibm_db2 extension could use the
db2_server_info()->MAX_COL_NAME_LEN property to dynamically display text fields for naming
columns with maximum lengths that correspond to the maximum length of column names on the
database management system to which it is connected.
For more information about the ibm_db2 API, see http://www.php.net/docs.php.
Examples
Example 1: Display a list of columns and associated privileges for a table
<?php
$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');
30 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
if ($conn) {
$stmt = db2_column_privileges($conn, NULL, NULL, 'DEPARTMENT');
$row = db2_fetch_array($stmt);
print $row[2] . "\n";
print $row[3] . "\n";
print $row[7];
db2_close($conn);
}
else {
echo db2_conn_errormsg();
printf("Connection failed\n\n");
}
?>
<?php
$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');
if ($conn) {
$stmt = db2_primary_keys($conn, NULL, NULL, 'DEPARTMENT');
while ($row = db2_fetch_array($stmt)) {
echo "TABLE_NAME:\t" . $row[2] . "\n";
echo "COLUMN_NAME:\t" . $row[3] . "\n";
echo "KEY_SEQ:\t" . $row[4] . "\n";
}
db2_close($conn);
}
else {
echo db2_conn_errormsg();
printf("Connection failed\n\n");
}
?>
<?php
$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');
if ($conn) {
$stmt = db2_procedures($conn, NULL, 'SYS%', '%%');
$row = db2_fetch_assoc($stmt);
var_dump($row);
db2_close($conn);
}
else {
echo "Connection failed.\n";
}
?>
<?php
$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');
if ($conn) {
echo "Test DEPARTMENT table:\n";
$result = db2_statistics($conn, NULL, NULL, "EMPLOYEE", 1);
while ($row = db2_fetch_assoc($result)) {
var_dump($row);
}
db2_close($conn);
}
else {
Example 5: Display a list of tables and their associated privileges in the database
<?php
$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');
if ($conn) {
$stmt = db2_table_privileges($conn, NULL, "%%", "DEPARTMENT");
while ($row = db2_fetch_assoc($stmt)) {
var_dump($row);
}
db2_close($conn);
}
else {
echo db2_conn_errormsg();
printf("Connection failed\n\n");
}
?>
You must set up the PHP 5.1 (or later) environment on your system and enable the PDO and PDO_IBM
extensions.
This procedure returns a connection object to an IBM data server database. This connection stays open
until you set the PDO object to NULL, or the PHP script finishes.
Procedure
To connect to an IBM data server database:
1. Create a connection to the database by calling the PDO constructor within a try{} block. Pass a DSN
value that specifies ibm: for the PDO_IBM extension, followed by either a cataloged database name
or a complete database connection string for a direct TCP/IP connection.
• (Windows): By default, the PDO_IBM extension uses connection pooling to minimize connection
resources and improve connection performance.
• (Linux and UNIX): To create a persistent connection, pass array(PDO::ATTR_PERSISTENT =>
TRUE) as the driver_options (fourth) argument to the PDO constructor.
2. Optional: Set error handling options for the PDO connection in the fourth argument to the PDO
constructor:
• By default, PDO sets an error message that can be retrieved through PDO::errorInfo() and an
SQLCODE that can be retrieved through PDO::errorCode() when any error occurs; to request this
mode explicitly, set PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT
32 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
• To issue a PHP E_WARNING when any error occurs, in addition to setting the error message and
SQLCODE, set PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING
• To throw a PHP exception when any error occurs, set PDO::ATTR_ERRMODE =>
PDO::ERRMODE_EXCEPTION
3. Catch any exception thrown by the try{} block in a corresponding catch {} block.
For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.
Example
Connect to an IBM data server database over a persistent connection.
try {
$connection = new PDO("ibm:SAMPLE", "db2inst1", "ibmdb2", array(
PDO::ATTR_PERSISTENT => TRUE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
}
catch (Exception $e) {
echo($e->getMessage());
}
What to do next
Procedure
To prepare and execute a single SQL statement that accepts no input parameters, call one of the listed
methods:
• To execute an SQL statement that returns no result set, call the PDO::exec method on the PDO
connection object, passing in a string that contains the SQL statement. For example, a typical use of
PDO::exec is to set the default schema for your application in a common include file or base class.
If the SQL statement succeeds (successfully inserts, modifies, or deletes rows), the PDO::exec
method returns an integer value representing the number of rows that were inserted, modified, or
deleted.
To determine if the PDO::exec method failed (returned FALSE or 0), use the === operator to strictly
test the returned value against FALSE.
• To execute an SQL statement that returns one or more result sets, call the PDO::query method on
the PDO connection object, passing in a string that contains the SQL statement. For example, you
might want to call this method to execute a static SELECT statement.
Example
Example 1: Call the PDO::exec method to set the default schema for your application
What to do next
If you called the PDO::query method to create a PDOStatement object, you can begin retrieving rows
from the object by calling the PDOStatement::fetch or PDOStatement::fetchAll method.
Procedure
To prepare and execute an SQL statement that includes parameter markers:
1. Call the PDO::prepare method, passing the listed arguments:
statement
A string that contains the SQL statement, including question marks (?) or named variables (:name)
as parameter markers for any column or predicate values that require variable input. You can only
use parameter markers as a place holder for column or predicate values. The SQL compiler is
unable to create an access plan for a statement that uses parameter markers in place of column
names, table names, or other SQL identifiers. You cannot use both question mark (?) parameter
markers and named parameter markers (:name) in the same SQL statement.
driver_options
Optional: An array that contains statement options:
PDO::ATTR_CURSOR
This option sets the type of cursor that PDO returns for result sets. By default, PDO returns a
forward-only cursor (PDO::CURSOR_FWDONLY), which returns the next row in a result set for
34 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
every call to PDOStatement::fetch(). You can set this parameter to
PDO::CURSOR_SCROLL to request a scrollable cursor.
If the function call succeeds, it returns a PDOStatement object that you can use in subsequent method
calls that are related to this query.
If the function call fails (returns False), you can use the PDO::errorCode or PDO::errorInfo
method to retrieve diagnostic information about the error.
2. Optional: For each parameter marker in the SQL string, call the PDOStatement::bindParam
method, passing the listed arguments. Binding input values to parameter markers ensures that each
input value is treated as a single parameter, which prevents SQL injection attacks against your
application.
parameter
A parameter identifier. For question mark parameter markers (?), this is an integer that represents
the 1-indexed position of the parameter in the SQL statement. For named parameter markers
(:name), this is a string that represents the parameter name.
variable
The value to use in place of the parameter marker
3. Call the PDOStatement::execute method, optionally passing an array that contains the values to
use in place of the parameter markers, either in order for question mark parameter markers, or as
a :name => value associative array for named parameter markers.
For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.
Example
Prepare and execute a statement that includes variable input.
$sql = "SELECT firstnme, lastname FROM employee WHERE bonus > ? AND bonus < ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
// Handle errors
}
$stmt->execute($stmt);
What to do next
If the SQL statement returns one or more result sets, you can begin fetching rows from the statement
resource by calling the PDOStatement::fetch or PDOStatement::fetchAll method.
Procedure
To insert a large object into the database directly from a file:
1. Call the PDO::prepare method to create a PDOStatement object from an INSERT statement with a
parameter marker that represents the large object column.
Example
Insert a large object into the database.
You must have a statement resource returned by either the PDO::query or PDOStatement::execute
method that has one or more associated result sets.
Procedure
To fetch data from a result set:
1. Fetch data from a result set by calling one of the fetch methods:
• To return a single row from a result set as an array or object, call the PDOStatement::fetch
method.
• To return all of the rows from the result set as an array of arrays or objects, call the
PDOStatement::fetchAll method.
By default, PDO returns each row as an array indexed by the column name and 0-indexed column
position in the row. To request a different return style, specify one of the PDO::FETCH_* constants as
the first parameter when you call the PDOStatement::fetch method:
PDO::FETCH_ASSOC
Returns an array indexed by column name as returned in your result set.
PDO::FETCH_BOTH (default)
Returns an array indexed by both column name and 0-indexed column number as returned in your
result set
PDO::FETCH_BOUND
Returns TRUE and assigns the values of the columns in your result set to the PHP variables to
which they were bound with the PDOStatement::bindParam method.
36 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
PDO::FETCH_CLASS
Returns a new instance of the requested class, mapping the columns of the result set to named
properties in the class.
PDO::FETCH_INTO
Updates an existing instance of the requested class, mapping the columns of the result set to
named properties in the class.
PDO::FETCH_LAZY
Combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they
are accessed.
PDO::FETCH_NUM
Returns an array indexed by column number as returned in your result set, starting at column 0.
PDO::FETCH_OBJ
Returns an anonymous object with property names that correspond to the column names returned
in your result set.
If you requested a scrollable cursor when you called the PDO::query or PDOStatement::execute
method, you can pass the listed optional parameters that control which rows are returned to the
caller:
• One of the PDO::FETCH_ORI_* constants that represents the fetch orientation of the fetch request:
PDO::FETCH_ORI_NEXT (default)
Fetches the next row in the result set.
PDO::FETCH_ORI_PRIOR
Fetches the previous row in the result set.
PDO::FETCH_ORI_FIRST
Fetches the first row in the result set.
PDO::FETCH_ORI_LAST
Fetches the last row in the result set.
PDO::FETCH_ORI_ABS
Fetches the absolute row in the result set. Requires a positive integer as the third argument to
the PDOStatement::fetch method.
PDO::FETCH_ORI_REL
Fetches the relative row in the result set. Requires a positive or negative integer as the third
argument to the PDOStatement::fetch method.
• An integer requesting the absolute or relative row in the result set, corresponding to the fetch
orientation requested in the second argument to the PDOStatement::fetch method.
2. Optional: Fetch a single column from one or more rows in a result set by calling one of the listed
methods:
• To return a single column from a single row in the result set:
Call the PDOStatement::fetchColumn method, specifying the column you want to retrieve as
the first argument of the method. Column numbers start at 0. If you do not specify a column, the
PDOStatement::fetchColumn returns the first column in the row.
• To return an array that contains a single column from all of the remaining rows in the result set:
Call the PDOStatement::fetchAll method, passing the PDO::FETCH_COLUMN constant as the
first argument, and the column you want to retrieve as the second argument. Column numbers start
at 0. If you do not specify a column, calling PDOStatement::fetchAll(PDO::FETCH_COLUMN)
returns the first column in the row.
For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.
What to do next
When you are ready to close the connection to the database, set the PDO object to NULL. The connection
closes automatically when the PHP script finishes.
Procedure
To fetch a large object from the database directly into a file:
1. Create a PHP variable representing a stream. For example, assign the return value from a call to the
fopen function to a variable.
2. Create a PDOStatement object from an SQL statement by calling the PDO::prepare method.
3. Bind the output column for the large object to the PHP variable representing the stream by calling the
PDOStatement::bindColumn method. The second argument is a string representing the name of
the PHP variable that holds the path and name of the file. The third argument is a PHP constant,
PDO::PARAM_LOB, which tells the PDO extension to write the data into a file. You must call the
PDOStatement::bindColumn method to assign a different PHP variable for every column in the
result set.
4. Issue the SQL statement by calling the PDOStatement::execute method.
5. Call PDOStatement::fetch(PDO::FETCH_BOUND) to retrieve the next row in the result set, binding
the column output to the PHP variables that you associated when you called the
PDOStatement::bindColumn method.
Example
Fetch a large object from the database directly into a file.
38 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
About this task
This procedure prepares and executes an SQL CALL statement. For more information, also see the topic
about preparing and executing SQL statements.
Procedure
To call a stored procedure:
1. Call the PDO::prepare method to prepare a CALL statement with parameter markers that represent
the OUT and INOUT parameters.
2. For each parameter marker in the CALL statement, call the PDOStatement::bindParam method to
bind each parameter marker to the name of the PHP variable that will hold the output value of the
parameter after the CALL statement has been issued. For INOUT parameters, the value of the PHP
variable is passed as the input value of the parameter when the CALL statement is issued.
a) Set the third parameter, data_type, to one of the PDO::PARAM_* constants that specifies the type
of data being bound:
PDO::PARAM_NULL
Represents the SQL NULL data type.
PDO::PARAM_INT
Represents SQL integer types.
PDO::PARAM_LOB
Represents SQL large object types.
PDO::PARAM_STR
Represents SQL character data types.
For an INOUT parameter, use the bitwise OR operator to append PDO::PARAM_INPUT_OUTPUT to
the type of data being bound.
b) Set the fourth parameter, length, to the maximum expected length of the output value.
3. Call the PDOStatement::execute method, passing the prepared statement as an argument.
For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.
Example
Prepare and execute an SQL CALL statement.
$stmt->execute();
Procedure
To retrieve multiple result sets:
1. Fetch rows from the first result set returned from the procedure by calling one of the PDO fetch
methods. (The first result set that is returned from the procedure is associated with the PDOStatement
object returned by the CALL statement.)
• To return a single row from a result set as an array or object, call the PDOStatement::fetch
method.
• To return all of the rows from the result set as an array of arrays or objects, call the
PDOStatement::fetchAll method.
Fetch rows from the PDOStatement object until no more rows are available in the first result set.
2. Retrieve the subsequent result sets by calling the PDOStatement::nextRowset method to return
the next result set. You can fetch rows from the PDOStatement object until no more rows are available
in the result set.
The PDOStatement::nextRowset method returns False when no more result sets are available or
the procedure did not return a result set.
For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.
Example
Retrieve multiple result sets from a stored procedure.
What to do next
When you are ready to close the connection to the database, set the PDO object to NULL. The connection
closes automatically when the PHP script finishes.
40 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
After you commit or rollback the transaction, PDO automatically resets the database connection to
autocommit mode.
For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.
Examples
End the transaction when PDO::commit or PDO::rollBack is called.
$conn->commit();
}
catch (Exception $e) {
// If something raised an exception in our transaction block of statements,
// roll back any work performed in the transaction
print '<p>Unable to complete transaction!</p>';
$conn->rollBack();
}
You must set up the PHP environment on your system and enable the PDO and PDO_IBM extensions.
PDO gives you the option of handling errors as warnings, errors, or exceptions. However, when you create
a new PDO connection object, PDO always throws a PDOException object if an error occurs. If you do not
catch the exception, PHP prints a backtrace of the error information that might expose your database
connection credentials, including your user name and password.
This procedure catches a PDOException object and handles the associated error.
Procedure
1. To catch a PDOException object and handle the associated error:
a) Wrap the call to the PDO constructor in a try block.
b) Following the try block, include a catch block that catches the PDOException object.
c) Retrieve the error message associated with the error by invoking the Exception::getMessage
method on the PDOException object.
2. To retrieve the SQLSTATE associated with a PDO or PDOStatement object, invoke the errorCode
method on the object.
3. To retrieve an array of error information associated with a PDO or PDOStatement object, invoke the
errorInfo method on the object. The array contains a string representing the SQLSTATE as the first
element, an integer representing the SQL or CLI error code as the second element, and a string
containing the full text error message as the third element.
For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.
2 Includes Windows binaries. Most Linux distributions come with Python already precompiled.
Procedure
To set up the Python environment:
44 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
1. Using the following method, install the ibm_db Python driver:
• Install from the remote repository:
a. If you want to avoid automatic installation of the clidriver and would like to use an existing copy
of the driver, you can set IBM_DB_HOME.
Set the IBM_DB_HOME environment variable by using the export command:
$ export IBM_DB_HOME=DB2HOME
where DB2HOME is the directory where the IBM data server product is installed.
For example, issue the following command to set the IBM_DB_HOME environment variable:
or
$ easy_install ibm_db
2. Optional: Using the following method, install the ibm_db_sa SQLAlchemy adapter or ibm_db_django
Django adapter:
• Install from the remote repository:
– To install the SQLAlchemy adapter, issue the following command:
or
$ easy_install ibm_db_sa
or
$ easy_install ibm_db_django
3. Ensure that the Python driver can access the libdb2.so CLI driver file:
• For 32-bit Linux and UNIX operating systems other than the AIX operating system, set the
LD_LIBRARY_PATH variable to the IBM_DB_HOME/lib32 directory by issuing the export
command:
$ export LD_LIBRARY_PATH=IBM_DB_HOME/lib32
• For 64-bit Linux and UNIX operating systems other than the AIX operating system, set the
LD_LIBRARY_PATH variable to the IBM_DB_HOME/lib64 directory by issuing the export
command:
$ export LD_LIBRARY_PATH=IBM_DB_HOME/lib64
• For a 32-bit AIX operating system, set the LIBPATH variable to theIBM_DB_HOME/lib32 directory
by issuing the export command:
$ export LIBPATH=IBM_DB_HOME/lib32
$ export LIBPATH=IBM_DB_HOME/lib64
What to do next
Test the ibm_db Python driver, the ibm_db_sa SQLAlchemy adapter, and the ibm_db_django Django
adapter connection by using the test applications.
Verifying the Python driver, SQLAlchemy adapter, and Django adapter installation
When the installation of the Python driver and optional adapters are complete, it is a good practice to test
the new Python environment to verify that installation is working.
Procedure
To verify that your Python installation is successful:
1. Using the python command, start the Python interpreter.
$ python
You must specify a valid database name (database), user ID (user), and password (password) in the
code. Successful connection indicates valid ibm_db Python driver installation.
3. Optional: Using the listed code, test the ibm_db_sa SQLAlchemy adapter:
import sqlalchemy
from sqlalchemy import *
import ibm_db_sa.ibm_db_sa
db2 = sqlalchemy.create_engine('ibm_db_sa://user:[email protected]:50000/database')
metadata = MetaData()
users = Table('STAFF', metadata,
Column('ID', Integer, primary_key = True),
Column('NAME', String(9), nullable = False),
Column('DEPT', Integer, nullable = False),
46 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Column('JOB', String(5), nullable = False)
)
You must specify a valid database name (database), user ID (user), and password (password) in the
sqlalchemy.create_engine argument string. Successful connection indicates valid
ibm_db_django Django adapter installation.
4. Optional: Using the listed code, test the ibm_db_django Django adapter:
a. Using the django-admin.py startproject command, create a new Django project:
b. Using the editor of your choice, edit DATABASES dictionary in the settings.py file to configure
access to the IBM database server:
DATABASES = {
'default': {
'ENGINE' : 'ibm_db_django',
'NAME' : 'database',
'USER' : 'user',
'PASSWORD' : 'password',
'HOST' : 'localhost',
'PORT' : '50000',
'PCONNECT' : True, #Optional property. It is true by default
}
}
You must specify a valid database name (database), user ID (user), password (password), host
name (localhost), and port number (50000) in the settings.py file entry.
c. Using the editor of your choice, add the following tuple of strings in the INSTALLED_APPS section
of the settings.py file:
'django.contrib.flatpages',
'django.contrib.redirects',
'django.contrib.comments',
'django.contrib.admin',
Procedure
Call one of the listed functions to establish connection to an IBM database server:
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")
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 execute SQL statements. Next, you prepare and execute SQL statements.
48 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Before you begin
Obtain a connection resource by calling one of the connection functions in the ibm_db API. For more
information, see “Connecting to an IBM database server in Python” on page 47.
Procedure
To prepare and execute a single SQL statement, call the ibm_db.exec_immediate function, passing the
listed arguments:
connection
A valid database connection resource that is returned from the ibm_db.connect or
ibm_db.pconnect function.
statement
A string that contains the SQL statement. This string can include an XQuery expression that is called
by the XMLQUERY function.
options
Optional: A dictionary that specifies the type of cursor to return for result sets. You can use this
parameter to request a scrollable cursor for database servers that support this type of cursor. By
default, a forward-only cursor is returned.
If the function call fails (returns False), you can use the ibm_db.stmt_error or
ibm_db.stmt_errormsg function to retrieve diagnostic information about the error.
If the function call succeeds, you can use the ibm_db.num_rows function to return the number of rows
that the SQL statement returned or affected. If the SQL statement returns a result set, you can begin
fetching the rows.
For more information about the ibm_db API, see https://github.com/ibmdb/python-ibmdb/wiki/APIs.
Example
Example 1: Execute a single SQL statement
import ibm_db
conn = ibm_db.connect("database","username","password")
stmt = ibm_db.exec_immediate(conn, "UPDATE employee SET bonus = '1000' WHERE job = 'MANAGER'")
print "Number of affected rows: ", ibm_db.num_rows(stmt)
What to do next
If the SQL statement returns one or more result sets, you can begin fetching rows from the statement
resource.
Example
Prepare and execute a statement that includes variable input.
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT EMPNO, LASTNAME FROM EMPLOYEE WHERE EMPNO > ? AND EMPNO < ?"
stmt = ibm_db.prepare(conn, sql)
max = 50
min = 0
# Explicitly bind parameters
ibm_db.bind_param(stmt, 1, min)
ibm_db.bind_param(stmt, 2, max)
ibm_db.execute(stmt)
# Process results
50 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
What to do next
If the SQL statement returns one or more result sets, you can begin fetching rows from the statement
resource.
You must have a statement resource that is returned by either the ibm_db.exec_immediate or
ibm_db.execute function that has one or more associated result sets.
Procedure
To fetch data from a result set:
1. Fetch data from a result set by calling one of the fetch functions.
Example
Example 1: Fetch rows from a result set by calling the ibm_db.fetch_both function
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
dictionary = ibm_db.fetch_both(stmt)
while dictionary != False:
print "The ID is : ", dictionary["EMPNO"]
print "The Name is : ", dictionary[1]
dictionary = ibm_db.fetch_both(stmt)
Example 2: Fetch rows from a result set by calling the ibm_db.fetch_tuple function
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
tuple = ibm_db.fetch_tuple(stmt)
while tuple != False:
print "The ID is : ", tuple[0]
print "The name is : ", tuple[1]
tuple = ibm_db.fetch_tuple(stmt)
Example 3: Fetch rows from a result set by calling the ibm_db.fetch_assoc function
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
dictionary = ibm_db.fetch_assoc(stmt)
while dictionary != False:
print "The ID is : ", dictionary["EMPNO"]
print "The name is : ", dictionary["FIRSTNME"]
dictionary = ibm_db.fetch_assoc(stmt)
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
while ibm_db.fetch_row(stmt) != False:
print "The Employee number is : ", ibm_db.result(stmt, 0)
print "The last name is : ", ibm_db.result(stmt, "LASTNAME")
What to do next
When you are ready to close the connection to the database, call the ibm_db.close function. If you
attempt to close a persistent connection that you created with ibm_db.pconnect, the close request
returns True, and the connection remains available for the next caller.
52 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Calling stored procedures in Python
To call a stored procedure from a Python application, use ibm_db.callproc function. The procedure
that you call can include input parameters (IN), output parameters (OUT), and input and output
parameters (INOUT).
Obtain a connection resource by calling one of the connection functions in the ibm_db API.
Procedure
Call the ibm_db.callproc function by passing the listed arguments:
connection
A valid database connection resource that is returned from the ibm_db.connect or
ibm_db.pconnect function.
procname
A valid stored procedure name
parameters
A tuple of parameters that matches the parameters that are declared in the stored procedure.
Example
To call a stored procedure with the ibm_db.callproc function:
import ibm_db
What to do next
If the procedure call returns one or more result sets, you can begin fetching rows from the statement
resource.
Procedure
To retrieve multiple result sets:
1. Fetch rows from the first result set returned from the procedure by calling one of the listed ibm_db
fetch functions, passing the statement resource as an argument. (The first result set that is returned
from the procedure is associated with the statement resource.)
Example
Retrieve multiple result sets from a stored procedure.
import ibm_db
conn = ibm_db.connect( "sample", "user", "password" )
if conn:
sql = 'CALL sp_multi()'
stmt = ibm_db.exec_immediate(conn, sql)
row = ibm_db.fetch_assoc(stmt)
while row != False :
print "The value returned : ", row
row = ibm_db.fetch_assoc(stmt)
stmt1 = ibm_db.next_result(stmt)
while stmt1 != False:
row = ibm_db.fetch_assoc(stmt1)
while row != False :
print "The value returned : ", row
row = ibm_db.fetch_assoc(stmt1)
stmt1 = ibm_db.next_result(stmt)
What to do next
When you are ready to close the connection to the database, call the ibm_db.close function. If you
attempt to close a persistent connection that you created by using ibm_db.pconnect, the close request
returns True, and the IBM data server client connection remains available for the next caller.
54 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Commit modes in Python applications
You can control how groups of SQL statements are committed by specifying a commit mode for a
connection resource. The ibm_db API supports two commit modes: autocommit and manual commit.
Autocommit mode
In autocommit mode, each SQL statement is a complete transaction, which is automatically
committed. Autocommit mode helps prevent locking escalation issues that can impede the
performance of highly scalable web applications. By default, the ibm_db API opens every connection
in autocommit mode.
If autocommit mode is disabled, you can enable the autocommit mode by calling
ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_ON), where conn is a valid connection
resource.
Calling the ibm_db.autocommit function might affect the performance of your Python scripts
because it requires additional communication between Python and the database management
system.
Manual commit mode
In manual commit mode, the transaction ends when you call the ibm_db.commit or
ibm_db.rollback function. This means that all statements executed on the same connection
between the start of a transaction and the call to the commit or rollback function are treated as a
single transaction.
Manual commit mode is useful if you might have to roll back a transaction that contains one or more
SQL statements. If you execute SQL statements in a transaction and the script ends without explicitly
committing or rolling back the transaction, the ibm_db extension automatically rolls back any work
that is performed in the transaction.
You can turn off autocommit mode when you create a database connection by using the
{ ibm_db.SQL_ATTR_AUTOCOMMIT: ibm_db.SQL_AUTOCOMMIT_OFF } setting in the
ibm_db.connect or ibm_db.pconnect options array. You can also turn off autocommit mode for a
connection resource by calling ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF),
where conn is a valid connection resource.
For more information about the ibm_db API, see https://github.com/ibmdb/python-ibmdb/wiki/APIs.
Examples
Turn off autocomit mode and end the transaction when ibm_db.commit or ibm_db.rollback is called.
import ibm_db
Connection errors
Use one of the listed functions to retrieve diagnostic information if a connection attempt fails.
SQL errors
Use one of the listed functions to retrieve diagnostic information if an attempt to prepare or execute an
SQL statement or to fetch a result from a result set fails.
Examples
Example 1: Handle connection errors
import ibm_db
try:
conn = ibm_db.connect("database","username","password")
except:
print "no connection:", ibm_db.conn_errormsg()
else:
print "The connection was successful"
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "DELETE FROM EMPLOYEE"
try:
stmt = ibm_db.exec_immediate(conn, sql)
except:
print "Transaction couldn't be completed:" , ibm_db.stmt_errormsg()
else:
print "Transaction complete."
56 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Table 16. ibm_db metadata retrieval functions (continued)
Function Description
Returns a result set listing
the columns and
associated privileges for a
table
Returns a result set listing
the columns and
associated metadata for a
table
Returns a result set listing
the foreign keys for a
table
Returns a result set listing
the primary keys for a
table
Returns a result set listing
the parameters for one or
more stored procedures
Returns a result set listing
the stored procedures
registered in a database
Examples
Example 1: Display information about the IBM data server client
import ibm_db
if client:
print "DRIVER_NAME: string(%d) \"%s\"" % (len(client.DRIVER_NAME), client.DRIVER_NAME)
print "DRIVER_VER: string(%d) \"%s\"" % (len(client.DRIVER_VER), client.DRIVER_VER)
print "DATA_SOURCE_NAME: string(%d) \"%s\"" % (len(client.DATA_SOURCE_NAME), client.DATA_SOURCE_NAME)
print "DRIVER_ODBC_VER: string(%d) \"%s\"" % (len(client.DRIVER_ODBC_VER), client.DRIVER_ODBC_VER)
print "ODBC_VER: string(%d) \"%s\"" % (len(client.ODBC_VER), client.ODBC_VER)
print "ODBC_SQL_CONFORMANCE: string(%d) \"%s\"" % (len(client.ODBC_SQL_CONFORMANCE), client.ODBC_SQL_CONFORMANCE)
print "APPL_CODEPAGE: int(%s)" % client.APPL_CODEPAGE
print "CONN_CODEPAGE: int(%s)" % client.CONN_CODEPAGE
ibm_db.close(conn)
else:
print "Error."
import ibm_db
if server:
print "DBMS_NAME: string(%d) \"%s\"" % (len(server.DBMS_NAME), server.DBMS_NAME)
print "DBMS_VER: string(%d) \"%s\"" % (len(server.DBMS_VER), server.DBMS_VER)
print "DB_NAME: string(%d) \"%s\"" % (len(server.DB_NAME), server.DB_NAME)
ibm_db.close(conn)
else:
print "Error."
58 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
Chapter 5. Developing Ruby on Rails applications
Procedure
To set up the Ruby on Rails environment with an IBM data server client:
1. Download and install the latest version of Ruby from http://www.ruby-lang.org/en/downloads/.
2. Install the Rails gem and its dependencies by issuing the gem installation command:
What to do next
You are now ready to install the IBM_DB Ruby driver and Rails adapter as a gem.
Installing the IBM_DB Ruby driver and Rails adapter as a Ruby gem
The IBM_DB Ruby driver and Rails adapter is available as a Ruby gem for installation in the IBM data
server clients. Ruby Gems is the standard packaging and installation framework for libraries and
applications in the Ruby runtime environment. A single file for each bundle is called a gem, which
complies to the standardized package format. This package is then distributed and stored in a central
repository, allowing simultaneous deployment of multiple versions of the same library or application.
3 Any references to non-IBM websites are provided for convenience only and do not in any manner serve as
an endorsement of those websites. The content available at those non-IBM websites is not part of any
materials relating to the IBM products described herein. Your use of any non-IBM website is at your own
risk.
require 'ibm_db'
or on Windows:
require 'mswin32/ibm_db'
Procedure
To install the IBM_DB Ruby driver and Rails adapter as a Ruby gem:
1. On all supported platforms, issue the gem install command to install the IBM_DB Ruby driver and
Rails adapter:
2. Before running any Ruby script that connects to the IBM database server, you must ensure that the
IBM_DB Ruby driver can access the CLI driver on Linux or UNIX platforms by adding the libdb2.so
file path to the LD_LIBRARY_PATH environmental variable. If the IBM_DB Ruby driver cannot access
the CLI driver, the missing libraries - libdb2.so.1 error message is returned to your Ruby
program.
When using the IBM Data Server Driver Package software, the libdb2.so file is in the
odbc_cli_driver/linux/clidriver/lib directory.
In the IBM data server product environment, libdb2.so is in the sqllib/lib/ path.
Verifying the IBM_DB Ruby driver installation with the interactive Ruby shell
To verify the IBM_DB Ruby driver installation, use the interactive Ruby shell (irb) to connect to the
database and issue a query.
Procedure
• To verify the Ruby driver installation with the interactive Ruby shell, run the listed commands:
C:\>irb
irb(main):001:0> require 'mswin32/ibm_db'
#If you are using Linux based platform issue require 'ibm_db')
=>true
irb(main):002:0> conn = IBM_DB.connect 'devdb','username','password'
=> #<IBM_DB::Connection:0x2dddf40>
#Here ‘devdb’ is the database cataloged in client’s
#database directory or db entry in the db2dsdriver.cfg file.
#To connect to a remote database you
#will need to specify all the necessary attributes like
#hostname, port etc as follows.
#IBM_DB.connect('DRIVER={IBM DB2 ODBC=DRIVER};DATABASE=devdb;HOSTNAME=myhost;
PORT=60000;PROTOCOL=TCPIP;UID=uname;PWD=password;','','')
irb(main):003:0> stmt = IBM_DB.exec conn,'select * from staff'
=> #<IBM_DB::Statement:0x2beaabc>
irb(main):004:0> IBM_DB.fetch_assoc stmt
#Fetches the first row of the result set
Procedure
1. Create a new Rails application by issuing the following command:
60 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create db
[......]
create log/server.log
create log/production.log
create log/development.log
create log/test.log
C:\>cd newapp
3. Optional: If you are using a Rails version before the Rails 2.0, you must register the IBM_DB adapter to
the list of connection adapters in the Rails framework. You can register the IBM_DB adapter to the list
of connection adapters in the Rails framework by manually adding ibm_db to the list of connection
adapters in <RubyHome>\gems\1.8\gems\activerecord-1.15.6\lib\active_record.rb at
approximately line 77:
4. To configure the connections for the Rails applications, edit the database.yml file. A sample
development section entry for the database.yml file is listed in the following example:
development:
adapter: ibm_db
username: db2inst1
password: secret
database: devdb # Database name
#schema: db2inst1
#host: localhost #Host on which the database resides
#port: 50000 #port to which the remote Dataserver is listening
6. Create the tools table in the devdb database by issuing the rake db:migrate command:
Procedure
Edit the database configuration details in rails_application_path\config\database.yml, and
specify the listed connection attributes:
Note: Changes to connection information in this file are applied when the Rails environment is initialized
during server startup. Any changes that you make after initialization do not affect the connections that are
created.
Schema, account, app_user, application and workstation are not supported for IBM Informix.
Examples
The example establishes a trusted connection and switches the user on the same connection.
def trusted_connection(database,hostname,port,auth_user,auth_pass,tc_user,tc_pass)
dsn = "DATABASE=#{database};HOSTNAME=#{hostname};PORT=#{port};PROTOCOL=TCPIP;UID=#{auth_user};PWD=#{auth_pass};"
conn_options = {IBM_DB::SQL_ATTR_USE_TRUSTED_CONTEXT => IBM_DB::SQL_TRUE}
tc_options = {IBM_DB::SQL_ATTR_TRUSTED_CONTEXT_USERID => tc_user, IBM_DB::SQL_ATTR_TRUSTED_CONTEXT_PASSWORD => tc_pass}
tc_conn = IBM_DB.connect dsn, '', '', conn_options
if tc_conn
puts "Trusted connection established successfully."
val = IBM_DB.get_option tc_conn, IBM_DB::SQL_ATTR_USE_TRUSTED_CONTEXT, 1
if val
userBefore = IBM_DB.get_option tc_conn, IBM_DB::SQL_ATTR_TRUSTED_CONTEXT_USERID, 1
#do some work as user 1
#....
#....
#switch the user
result = IBM_DB.set_option tc_conn, tc_options, 1
userAfter = IBM_DB.get_option tc_conn, IBM_DB::SQL_ATTR_TRUSTED_CONTEXT_USERID, 1
if userBefore != userAfter
puts "User has been switched."
#do some work as user 2
#....
#....
end
end
IBM_DB.close tc_conn
else
puts "Attempt to connect failed due to: #{IBM_DB.conn_errormsg}"
end
end
62 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
IBM_DB Rails adapter dependencies and consequences
The IBM_DB adapter (ibm_db_adapter.rb) has a direct dependency on the IBM_DB driver, which uses
IBM Data Server Driver for ODBC and CLI to connect to IBM data servers. The IBM Call Level Interface
(CLI) is a callable SQL interface to IBM data servers, which is Open Database Connectivity (ODBC)
compliant.
This dependency has several ramifications for the IBM_DB adapter and driver.
• Installation of IBM Data Server Driver for ODBC and CLI, which meets the IBM_DB requirement, is
required.
IBM Data Server Driver for ODBC and CLI is included with a full Db2 database install, or you can obtain it
separately
Note: The IBM Data Server Driver for ODBC and CLI is included in the listed client packages:
– IBM Data Server Client
– IBM Data Server Runtime Client
– IBM Data Server Driver Package
• Driver behavior can be modified outside of a Rails application with use of CLI and IBM data server driver
configuration keywords.
The CLI keywords that are set in the db2cli.ini file and IBM data server driver configuration
keywords in the IBM data server driver configuration file (db2dsdriver.cfg) affect Rails applications
in a same way as CLI applications. For example, CLI keywords can be used to set the current schema or
alter transactional elements such as turning off autocommit behavior.
• Any diagnostic gathering requires CLI driver tracing.
Because all requests through the IBM_DB driver are implemented through IBM Data Server Driver for
ODBC and CLI, the CLI trace facility can identify problems for applications that use the IBM_DB adapter
and driver.
A CLI trace captures all of the API calls made by an application to the IBM Data Server Driver for ODBC
and CLI (including all input parameters), and it captures all of the values returned from the driver to the
application. It is an interface trace that captures how an application interacts with the IBM Data Server
Driver for ODBC and CLI and offers information about the inner workings of the driver.
The IBM_DB Ruby driver and Rails adapter are not supported on JRuby
The IBM_DB adapter is not supported on JRuby.
The IBM_DB adapter is not supported on JRuby because (as stated in the JRuby Wiki, "Getting Started"):
"Many Gems will work fine in JRuby, however some Gems build native C libraries as part of their install
process. These Gems will not work in JRuby unless the Gem has also provided a Java™ equivalent to the
native library." For more information, see JRuby GitHub wiki.
The IBM_DB adapter relies on the IBM_DB Ruby driver (C extension) and the IBM Data Server Driver for
ODBC and CLI to access databases on IBM data servers. Alternatively, you can either use the regular C
implementation of Ruby, or use JDBC_adapter to access databases.
Index 65
exec_immediate function (ibm_db) 48 functions (continued)
execute function (ibm_db) Python (continued)
calling stored procedures 53 ibm_db.close 51, 53
executing SQL statements with variable input 49 ibm_db.column_privileges 56
execute method (Perl DBI) 6 ibm_db.columns 56
ibm_db.commit 55
ibm_db.conn_error 55
F ibm_db.conn_errormsg 55
fetch_assoc function (ibm_db) ibm_db.connect 47
fetching columns 51 ibm_db.exec_immediate 48
fetching multiple result sets 53 ibm_db.execute 49, 53
fetching rows 51 ibm_db.fetch_assoc 51, 53
fetch_both function (ibm_db) ibm_db.fetch_both 51, 53
fetching columns 51 ibm_db.fetch_row 51, 53
fetching multiple result sets 53 ibm_db.fetch_tuple 51, 53
fetching rows 51 ibm_db.foreign_keys 56
fetch_row function (ibm_db) ibm_db.next_result 53
fetching columns 51 ibm_db.pconnect 47
fetching multiple result sets 53 ibm_db.prepare 49, 53
fetching rows 51 ibm_db.primary_keys 56
fetch_tuple function (ibm_db) ibm_db.procedure_columns 56
fetching columns 51 ibm_db.procedures 56
fetching multiple result sets 53 ibm_db.result 51
fetching rows 51 ibm_db.rollback 55
fetchrow method (Perl DBI) 6 ibm_db.server_info 56
foreign_keys function (ibm_db) 56 ibm_db.special_columns 56
functions ibm_db.statistics 56
PHP ibm_db.stmt_error 55
db2_autocommit 27 ibm_db.stmt_errormsg 55
db2_bind_param 20, 22, 25 ibm_db.table_privileges 56
db2_client_info 29
db2_close 22, 26 H
db2_column_privileges 29
db2_columns 29 host variables
db2_commit 27 Perl 6
db2_conn_error 28
db2_conn_errormsg 28
db2_connect 17
I
db2_exec 19 ibm_db API
db2_execute 20, 22, 25 details 43
db2_fetch_array 22, 26 overview 47
db2_fetch_assoc 22, 26 IBM_DB Ruby driver and Rails adapter
db2_fetch_both 22, 26 dependencies 63
db2_fetch_object 22, 24 details 59
db2_fetch_row 22, 26 environment setup 59
db2_foreign_keys 29 installation verification 60
db2_next_result 26 JRuby support 63
db2_pconnect 17 Ruby gem installation 59
db2_prepare 20, 22, 25 trusted contexts 62
db2_primary_keys 29 ibm_db_dbi API
db2_procedure_columns 29 details 43
db2_procedures 29 ibm_db_sa adaptor
db2_result 22 details 43
db2_rollback 27 ibm_db2 API
db2_server_info 29 details 13
db2_special_columns 29 PHP application development 17
db2_statistics 29 trusted contexts 18
db2_stmt_error 28
db2_stmt_errormsg 28
db2_table_privileges 29 J
Python
JRuby
ibm_db.autocommit 55
IBM_DB Ruby driver and Rails adapter 63
ibm_db.bind_param 49, 53
ibm_db.client_info 56
66 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
L PDOStatement::bindParam method (PDO) 34, 35, 38
PDOStatement::execute method (PDO) 34, 35, 38
large objects (LOBs) PDOStatement::fetch method (PDO) 36, 38, 39
fetching PDOStatement::fetchAll method (PDO) 36, 39
PHP 24, 38 PDOStatement::fetchColumn method (PDO) 36
inserting PDOStatement::nextRowset method (PDO) 39
PHP 22, 35 Perl
connecting to a database 5
documentation 5
M downloads 5
metadata drivers 5
retrieving errors 8
PHP 29 fetching rows 6
Python 56 methods
methods connect 5
Perl disconnect 5
connect 5 err 8
disconnect 5 errstr 8
err 8 execute 6
errstr 8 fetchrow 6
execute 6 prepare 6
fetchrow 6 state 8
prepare 6 overview 5
state 8 parameter markers 8
PHP problem reporting 5
PDO::beginTransaction 40 pureXML support 8
PDO::commit 40 restrictions 8
PDO::exec 33 sample programs 10, 11
PDO::prepare 34, 35, 38 SQLCODE variables 8
PDO::query 33 SQLSTATE variables 8
PDO::rollBack 40 PHP
PDOStatement::bindColumn 38 application development 13, 17, 32
PDOStatement::bindParam 34, 35, 38 connecting to database 17, 32
PDOStatement::execute 34, 35, 38 database metadata retrieval 29
PDOStatement::fetch 36, 38, 39 documentation 13
PDOStatement::fetchAll 36, 39 downloads 13
PDOStatement::fetchColumn 36 error handling 28, 41
PDOStatement::nextRowset 39 extensions for IBM data servers 13
fetching columns 22, 36
fetching large objects 24, 38
N fetching rows 22, 36
functions
next_result function (ibm_db) 53
db2_autocommit 27
node-ibm_db driver
db2_bind_param 25
installing 1
db2_client_info 29
overview 1
db2_close 22, 26
resources 1
db2_column_privileges 29
test connection 2
db2_columns 29
db2_commit 27
P db2_conn_error 28
db2_conn_errormsg 28
parameter markers db2_connect 17
Perl 8 db2_exec 19
pconnect function (ibm_db) 47 db2_execute 25
pdo_ibm db2_fetch_array 22, 26
details 13 db2_fetch_assoc 22, 26
developing PHP applications 32 db2_fetch_both 22, 26
PDO::beginTransaction method (PDO) 40 db2_fetch_object 22, 24
PDO::commit method (PDO) 40 db2_fetch_row 22, 26
PDO::exec method (PDO) 33 db2_foreign_keys 29
PDO::prepare method (PDO) 34, 35, 38 db2_next_result 26
PDO::query method (PDO) 33 db2_pconnect 17
PDO::rollBack method (PDO) 40 db2_prepare 25
PDOStatement::bindColumn method (PDO) 38 db2_primary_keys 29
Index 67
PHP (continued) Python (continued)
functions (continued) downloading extensions 43
db2_procedure_columns 29 error handling 55
db2_procedures 29 extensions for IBM data servers 43
db2_result 22 fetching rows 51
db2_rollback 27 functions
db2_server_info 29 ibm_db.autocommit 55
db2_special_columns 29 ibm_db.bind_param 49, 53
db2_statistics 29 ibm_db.client_info 56
db2_stmt_error 28 ibm_db.close 51, 53
db2_stmt_errormsg 28 ibm_db.column_privileges 56
db2_table_privileges 29 ibm_db.columns 56
IBM data server environment setup (Windows) 14 ibm_db.commit 55
ibm_db2 API ibm_db.conn_error 55
connecting to database 17 ibm_db.conn_errormsg 55
overview 17 ibm_db.connect 47
large objects 22, 35 ibm_db.exec_immediate 48
methods ibm_db.execute 49, 53
PDO::beginTransaction 40 ibm_db.fetch_assoc 51, 53
PDO::commit 40 ibm_db.fetch_both 51, 53
PDO::exec 33 ibm_db.fetch_row 51, 53
PDO::prepare 34, 35, 38 ibm_db.fetch_tuple 51, 53
PDO::query 33 ibm_db.foreign_keys 56
PDO::rollBack 40 ibm_db.next_result 53
PDOStatement::bindColumn 38 ibm_db.pconnect 47
PDOStatement::bindParam 34, 35, 38 ibm_db.prepare 49, 53
PDOStatement::execute 34, 35, 38 ibm_db.primary_keys 56
PDOStatement::fetch 36, 38, 39 ibm_db.procedure_columns 56
PDOStatement::fetchAll 36, 39 ibm_db.procedures 56
PDOStatement::fetchColumn 36 ibm_db.result 51
PDOStatement::nextRowset 39 ibm_db.rollback 55
PDO_IBM extension ibm_db.server_info 56
connecting to database 32 ibm_db.special_columns 56
executing single statement 33 ibm_db.statistics 56
procedures 25, 38 ibm_db.stmt_error 55
setup ibm_db.stmt_errormsg 55
Linux 15 ibm_db.table_privileges 56
overview 14 IBM data server environment setup 44
UNIX 15 ibm_db 47
SQL statements installation verification 46
executing (overview) 19, 33 procedures 53
executing single statement 19, 33 SQL statements 48, 49
executing statements with variable input 20, 34 stored procedures
preparing statements with variable input 20, 34 calling 53
stored procedures retrieving results 53
calling 25, 38 transactions 55
retrieving results 26, 39
transactions 27, 40
trusted contexts 18
R
prepare function (ibm_db) 49, 53 RadRails
prepare method (Perl DBI) 6 IBM data server on Rails setup 59
primary_keys function (ibm_db) 56 Rails adapter
procedure_columns function (ibm_db) 56 dependencies 63
procedures details 59
PHP 25, 38 getting started 59
Python 53 installation verification 60
procedures function (ibm_db) 56 installing 59
pureXML JRuby support 63
DB2::DB2 driver 8 Rails applications
Python connection configuration 62
API documentation 43 result function (ibm_db) 51
application development 43, 47 rollback function (ibm_db) 55
connecting to database 47 rows
database metadata retrieval 56 fetching
68 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
rows (continued)
fetching (continued)
Perl 6
PHP 22, 36
Python 51
Ruby driver
details 59
getting started 59
IBM_DB Ruby driver and Rails adapter installation 59
installation verification 60
JRuby support 63
trusted contexts 62
Ruby on Rails
heap size issues 63
S
samples
Perl 10, 11
server_info function (ibm_db) 56
special_columns function (ibm_db) 56
SQL statements
PHP 19, 20, 22, 33–36, 38
Python 48, 49
SQLAlchemy
adapter for IBM data servers 43
downloading extension 43
IBM data server environment setup 44
installation verification 46
state method 8
static SQL
Perl 8
statistics function (ibm_db) 56
stmt_error function (ibm_db) 55
stmt_errormsg function (ibm_db) 55
stored procedures
PHP
calling 25, 38
retrieving results 26, 39
Python
calling 53
retrieving results 53
retrieving result sets
PHP 26, 39
Python 53
T
table_privileges function (ibm_db) 56
transactions
PHP 27, 40
Python 55
trusted contexts
IBM_DB Ruby driver support 62
PHP applications 18
Index 69
70 IBM Db2 V11.5: Developing Node.JS, Perl, PHP, Python, and Rubyon Rails Applications
IBM®