Skip to main content

skip to main content

developerWorks  >  Information Management  >

DB2 UDB connectivity cheat sheets: Part 5

Setting up connectivity for ADO and ADO.NET application developers

developerWorks
Document options

Document options requiring JavaScript are not displayed

Sample code


My developerWorks needs you!

Connect to your technical community


Rate this page

Help us improve this content


Level: Introductory

Jalud Abdulmenan (jalud@rogers.ca), Database consultant
Raul Chong (rfchong@ca.ibm.com), Database consultant, IBM

05 Feb 2004

This is the fifth article in a series discussing connectivity scenarios involving DB2 UDB for Linux, UNIX and Windows version 8, DB2 UDB for iSeries 5.2 and DB2 UDB for z/OS V8. The focus of this article is on workstation application development connectivity for ADO and ADO.NET applications accessing DB2 using C++, Visual Basic, C#, and Visual Basic .NET languages.

Introduction

This is the fifth article discussing connectivity scenarios involving IBM® DB2® Universal Database (UDB) for Linux, UNIX® and Windows® Version 8, DB2 UDB for iSeries 5.2 and DB2 UDB for z/OS V8*. As in the third and fourth parts of this article series, the latest versions are being used; however, the instructions shown may apply to other versions.

The focus of this article is on workstation application development connectivity. This means we will provide sample programs developed on workstation platforms (Windows) using ADO and ADO.NET, where each program connects to a DB2 UDB database (any platform), selects from a table, and disconnects. The sample programs have been tested on a Microsoft® Windows 2000 platform. Due to space limitations, the listings in this article contain only code snippets. However, we provide at the end of this article the source code of the complete functional sample programs in a zip file. We also provide step-by-step guides on how to create the sample programs using Microsoft Visual Studio 6 and Microsoft Visual Studio .NET.

Due to space constraints in this article, we also are not showing the output of the sample programs; however, the file ADO_ADONET_Results.zip contains the print screens of the tests that were performed using all of the sample programs against a DB2 UDB for Linux, UNIX and Windows, DB2 UDB for zSeries, and DB2 UDB for iSeries server.

Working as a consultant, I have encountered situations where a sample program would have been handy to test if the application connectivity setup was correct. The sample programs in this article can be used for this purpose. With DB2 UDB for Linux, UNIX and Windows V8 you can now test several types of connections using the Configuration Assistant (CA); however, the sample programs will be handy for previous version of DB2 UDB and also they give you more detail on the connectivity setup.

This article should be useful also to database administrators (DBAs) who normally don't need to code programs. Having a basic understanding about how to write a program against a DB2 database should be advantageous to them when interacting with their application developers.

The programs in this article have been based on the sample programs supplied with the DB2 UDB Application Development client (under directory sqllib/samples); however, they have been simplified for ease of understanding.

This article describes the following connectivity scenarios:



Back to top


Scenario 1 - Connecting to a DB2 UDB database using the IBM OLE DB provider for DB2 (IBMDADB2)


Figure 1 - DB2 UDB for Windows application client to DB2 UDB (any platform) using the IBM OLE DB Provider (IBMDADB2)
Graphical representation of DB2 UDB for Windows application client to DB2 UDB (any platform) using the IBM OLE DB Provider (IBMDADB2)

Listing 1 and Listing 2 show how to connect to a DB2 database using the MS OLE DB Provider for ODBC and issue a simple select statement. You can find the sample applications dbConn_vb_ado_ibmdadb2.bas and dbConn_vc_ado_ibmdadb2.cpp in the source code zip file here.


Listing 1: Visual Basic ADO code snippet (IBM OLE DB Provider for DB2)
			
Dim cmd As ADODB.Command
Dim con As ADODB.Connection
Dim rst As ADODB.Recordset

Set con = New ADODB.Connection
con.ConnectionString = "DSN=SAMPLE;UID=db2admin;PWD=mypsw;"
con.Provider = "IBMDADB2"
con.CursorLocation = adUseClient
con.Open

Set cmd = New ADODB.Command
Set cmd.ActiveConnection = con
cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1"
Set rst = cmd.Execute()
MsgBox "Successful retrieval of record. Column" + _
           " 'IBMREQD' has a value of '" + _
           rst.Fields.Item("IBMREQD").Value + "'" + vbCrLf

rst.Close
con.Close


Listing 2: Visual C++ ADO code snippet (IBM OLE DB Provider for DB2)
			
#import "C:\program files\common files\system\ado\msado15.dll" \
	no_namespace rename( "EOF", "adoEOF")
[...]
_CommandPtr pCmd  = NULL;			
_ConnectionPtr pConnection = NULL;	
_RecordsetPtr  pRst = NULL;
_bstr_t strMsg;
HRESULT  hr;
try {
    hr = pConnection.CreateInstance(__uuidof(Connection));
    if FAILED(hr) { _com_issue_error(hr);}
    pConnection->ConnectionString =     
                         _bstr_t("DSN=sample;UID=db2admin;PWD=mypsw;");
    pConnection->CursorLocation = adUseClient;
    pConnection->Provider = "IBMDADB2";
    pConnection->Open("","","",adConnectUnspecified);
    
    hr = pCmd.CreateInstance(__uuidof(Command));
    if FAILED(hr){_com_issue_error(hr);}
    pCmd->ActiveConnection = pConnection;
    pCmd->CommandText = _bstr_t("SELECT * FROM SYSIBM.SYSDUMMY1");       
    pRst = pCmd->Execute(NULL,NULL,adOptionUnspecified); 
    strMsg  = _bstr_t("  Successful retrieval of record.");
    strMsg += _bstr_t(" Column 'IBMREQD' has a value of '");
    strMsg += _bstr_t(pRst->Fields->Item["IBMREQD"]->Value) ;
    strMsg += _bstr_t("'");
    printf("%s\n",(LPCSTR)strMsg);

    pRst->Close();
    pConnection->Close();
} catch(_com_error &e) { [...] }

Table 1 - DB2 UDB for Windows to DB2 UDB server (any platform) using IBM OLE DB provider for DB2

Machine 1 ('myblue') DB2 UDB for Windows

Machine 2 ('aries') DB2 UDB server (any platform)

Commands to run on this machine:

Information you need to obtain from this machine, to perform the commands on machine 1

Part I: Configuring connectivity

Refer to part 1 of this article series for detailed connectivity setup instructions.

Part II: Compiling the programs that use the IBM OLE DB provider for DB2

vb6 /m dbConn_vb_ado_ibmdadb2.vbp

For details see step-by-step guide 1

msdev dbConn_vc_ado_ibmdadb2.dsp /make "dbConn_vc_ado_ibmdadb2 - Win32 Release" /rebuild

For details see step-by-step guide 2

Things to notice:

  • Use Table 3 as a guide when specifying the Connection object properties
  • The CursorLocation property on the Connection object affects your choice of CursorType and LockType on the Recordset Object, see Table 4
  • When specifying the ConnectionString property do not use single quotes to enclose the DSN, UID, and PWD keyword/value pairs
  • Your code must reference the ADO type library (msado15.dll or other version msado<xx>.dll) typically found at C:\Program Files\Common Files\System\ADO
  • You do not need to catalog the DB2 database as an ODBC data source

*Note: The IBM OLE DB provider for DB2 (ibmdadb2.dll) is typically located at sqllib\bin

To compile the sample programs, you need:

  • DB2 Application Development Client
  • Microsoft Data Access Components (MDAC) 2.7 or higher
  • Microsoft Visual Studio 6 with Service Pack 5

The dbalias is used to connect to the database. When a dbalias is not provided in the Catalog command (per part I above), the dbalias is the same as the dbname.

Part III: Executing the program

dbConn_vb_ado_ibmdadb2.exe sample db2admin mypsw

dbConn_vc_ado_ibmdadb2.exe sample db2admin mypsw

* The sample programs were designed to take 3 arguments in this order: <database name> <userid> <password>

sample = Database name

db2admin = User id on the server

mypsw = Password on the server



Back to top


Scenario 2 - Connecting to a DB2 UDB database using the Microsoft OLE DB Provider for ODBC (MSDASQL)


Figure 2 - DB2 UDB for Windows application client to DB2 UDB (any platform) using the Microsoft OLE DB Provider for ODBC (MSDASQL)
Graphical representation of DB2 UDB for Windows application client to DB2 UDB (any platform) using the Microsoft OLE DB Provider for ODBC (MSDASQL)

Listing 3 and Listing 4 show how to connect to a DB2 database using the MS OLE DB Provider for ODBC and issue a simple select statement. You can find the sample applications dbConn_vb_ado_msdasql.bas and dbConn_vc_ado_msdasql.cpp in the source code zip file here.


Listing 3: Visual Basic ADO code snippet (Microsoft OLE DB Provider for ODBC)
			
Dim cmd As ADODB.Command
Dim con As ADODB.Connection
Dim rst As ADODB.Recordset

Set con = New ADODB.Connection
con.ConnectionString = "DSN=SAMPLE;UID=db2admin;" + _
                 "PWD=mypsw;Driver={IBM DB2 ODBC DRIVER};"
con.Provider = "MSDASQL"
con.CursorLocation = adUseClient
con.Open

Set cmd = New ADODB.Command
Set cmd.ActiveConnection = con
cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1"
Set rst = cmd.Execute()
MsgBox "Successful retrieval of record. Column" + _
         " 'IBMREQD' has a value of '" + _
          rst.Fields.Item("IBMREQD").Value + _
          "'" + vbCrLf
          
rst.Close
con.Close


Listing 4: Visual C++ ADO code snippet (Microsoft OLE DB Provider for ODBC)
			
#import "C:\program files\common files\system\ado\msado15.dll" \
	no_namespace rename( "EOF", "adoEOF")
[...]
_CommandPtr pCmd  = NULL;			
_ConnectionPtr pConnection = NULL;		
_RecordsetPtr  pRst = NULL;
_bstr_t strMsg;			
HRESULT  hr;	
try{
    hr = pConnection.CreateInstance(__uuidof(Connection));
    if FAILED(hr){_com_issue_error(hr);}
    pConnection->ConnectionString= _bstr_t("DSN=sample;
    		UID=db2admin;PWD=mypsw;Driver={IBM DB2 ODBC DRIVER};");
    pConnection->CursorLocation = adUseClient;
    pConnection->Provider = "MSDASQL";
    pConnection->Open("","","",adConnectUnspecified);
    
    hr = pCmd.CreateInstance(__uuidof(Command));
    if FAILED(hr) {_com_issue_error(hr);}
    pCmd->ActiveConnection = pConnection;
    pCmd->CommandText = _bstr_t("SELECT * FROM SYSIBM.SYSDUMMY1");
    pRst = pCmd->Execute(NULL,NULL,adOptionUnspecified); 
    strMsg  = _bstr_t("  Successful retrieval of record.");
    strMsg += _bstr_t(" Column 'IBMREQD' has a value of '");
    strMsg += _bstr_t(pRst->Fields->Item["IBMREQD"]->Value) ;
    strMsg += _bstr_t("'");
    printf("%s\n",(LPCSTR)strMsg);

    pRst->Close();
    pConnection->Close();
} catch(_com_error &e){ [...] }

Table 2 - DB2 UDB for Windows to DB2 UDB server (any platform) using Microsoft OLE DB Provider for ODBC

Machine 1 ('myblue') DB2 UDB for Windows

Machine 2 ('aries') DB2 UDB server (any platform)

Commands to run on this machine:

Information you need to obtain from this machine, to perform the commands on machine 1

Part I: Configuring connectivity

The DB2 database must cataloged as an ODBC data source. To catalog an ODBC data source:

db2 catalog system ODBC data source sample

or

db2 catalog user ODBC data source sample

To list ODBC data sources:

db2 list system ODBC data sources

or

db2 list user ODBC data sources

Refer to part 1 of this article series for detailed connectivity setup instructions and to part 4 for registering a database as an ODBC Data Source.

Part II: Compiling the programs that use the Microsoft OLE DB Provider for ODBC

vb6 /m dbConn_vb_ado_msdasql.vbp

For details see step-by-step guide 1

msdev dbConn_vc_ado_msdasql.dsp /make "dbConn_vc_ado_msdasql - Win32 Release" /rebuild

For details see step-by-step guide 2

Things to notice:

  • Use Table 3 as a guide when specifying the Connection object properties
  • The CursorLocation property on the Connection object affects your choice of CursorType and LockType on the Recordset Object, see Table 4
  • When specifying the ConnectionString property do not use single quotes to enclose the DSN, UID, and PWD keyword/value pairs
  • Specify the Driver keyword/value in the ConnectionString: "Driver={IBM DB2 ODBC DRIVER};"
  • Your code must reference the ADO type library (msado15.dll or other version msado<xx>.dll) typically found at C:\Program Files\Common Files\System\ADO

*Note: The IBM OLE DB provider for DB2 (ibmdadb2.dll) is typically located at sqllib\bin

To compile the sample programs, you need

  • DB2 Application Development Client
  • Microsoft Data Access Components (MDAC) 2.7 or higher
  • Microsoft Visual Studio 6 with Service Pack 5

The dbalias is used to connect to the database. When a dbalias is not provided in the Catalog command (per part I above), the dbalias is the same as the dbname.

Part III: Executing the program

dbConn_vb_ado_msdasql.exe sample db2admin mypsw

dbConn_vc_ado_msdasql.exe sample db2admin mypsw

* The sample programs were designed to take 3 arguments in this order: <database name> <userid> <password>

sample = Database name

db2admin = User id on the server

mypsw = Password on the server

Table 3 - Connection object properties and values specific for connecting to a DB2 UDB database

ADO Connection object properties

Value

Connection String

"DSN=sample;UID=db2admin;PWD=mypsw;Driver={IBM DB2 ODBC DRIVER};"

Specify only when using MS OLE DB Provider for ODBC

(DB2 CLI keyword-value pair can also be specified)

CursorLocation

adUseClient

(Updatable bi-directional cursor)

or

adUseServer

(None-updatable forward only cursor)

Mode

adModeReadWrite

Provider1

"IBMDADB2"

(IBM OLE DB Provider for DB2)

(Database need not be catalogued as an ODBC datasource)

or

"MSDASQL"

(MS OLE DB Provider for ODBC)

(Database must be catalogued as an ODBC datasource)

CommandTimeOut

30 (Specified in seconds) (Default)

or

0 (Wait indefinitely until execution is complete)

Attributes

0 (Default)

or

adXactAbortRetaining

(calling RollbackTrans automatically starts a new transaction)

or

adXactCommitRetaining

(calling CommitTrans automatically starts a new transaction)

or

adXactAbortRetaining+adXactCommitRetaining

(calling RollbackTrans automatically starts a new transaction and calling CommitTrans automatically starts a new transaction)

IsolationLevel

adXactReadCommitted (also adXactCursorStability) (Default)

(Cursor Stability - CS)

or

adXactIsolated (also adXactSerializable)

(Repeatable Read - RR)

or

adXactReadUncommitted

(Uncommitted Read - UR)

or

adXactRepeatableRead

(Read Stability - RS)

1You can also specify the provider in the Connection String property (i.e. Provider=IBMDADB2;). However, you should only specify either the Provider property or the provider argument in the Connection String property.

As shown in Table 4, the CursorLocation property of a Connection object constraints the values of the CursorType and LockType properties of the Recordset objects that are associated with it.

Table 4 - The CursorLocation property of a Connection object constraints the values of the CursorType and LockType properties of the Recordset object

CursorLocation (Connection object)

CursorType (Recordset object)

LockType2 (Recordset object)

adUseClient

adOpenStatic

adLockReadOnly

adUseServer

adOpenForwardOnly

adLockReadOnly

or

adLockPessimistic

2The LockType property is not supported by the IBM OLE DB provider for DB2.



Back to top


Scenario 3 - Connecting to a DB2 UDB database using the IBM DB2 .NET Data Provider


Figure 3 - DB2 UDB for Windows application client to DB2 UDB (any platform) using the IBM DB2 .NET Data Provider
Graphical representation of DB2 UDB for Windows application client to DB2 UDB (any platform) using the IBM DB2 .NET Data Provider

Listing 5 and Listing 6 show how to connect to a DB2 database using the IBM DB2 .NET Data Provider and issue a simple select statement. You can find the sample applications dbConn_vb_adoNET_ibmdatadb2.vb and dbConn_cs_adoNET_ibmdatadb2.cs in the source code zip file here.


Listing 5: Visual Basic ADO.NET code snippet (IBM DB2 .NET Data Provider)
			
Imports IBM.Data.DB2
[...]
Dim cmd As DB2Command
Dim con As DB2Connection
Dim rdr As DB2DataReader
Dim v_IBMREQD As String
Try
    con = New DB2Connection("Database=SAMPLE;" +
                            "UID=db2admin;PWD=mypsw;")
    cmd = New DB2Command()
    cmd.Connection = con
    cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1"
    cmd.CommandTimeout = 20
    con.Open()

    rdr = cmd.ExecuteReader(CommandBehavior.SingleResult)
    v_IBMREQD = "";
    while (rdr.Read() == true) {
        v_IBMREQD = rdr.GetString(0); }
    strMsg = "  Successful retrieval of record. Column " +
		  "'IBMREQD' has a value of '" +
		  v_IBMREQD + "'";
    Console.WriteLine(strMsg);
    
    rdr.Close()
    con.Close()
Catch myException As DB2Exception
	[...]
End Try


Listing 6: C# ADO.NET code snippet (IBM DB2 .NET Data Provider)
			
using IBM.Data.DB2;
[...]
DB2Command cmd = null;
DB2Connection con = null;
DB2DataReader rdr = null;
int rowCount;
try{
     con = new DB2Connection("Database=SAMPLE;UID=db2admin;PWD=mypsw;");
     cmd = new DB2Command();
     cmd.Connection = con;
     cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1";
     cmd.CommandTimeout = 20;
     con.Open();
     	
     rdr = cmd.ExecuteReader(CommandBehavior.SingleResult);
     v_IBMREQD = "";
     while (rdr.Read() == true) {
      v_IBMREQD = rdr.GetString(0); }
     strMsg = "  Successful retrieval of record. Column" +
     	    " 'IBMREQD' has a value of '" + v_IBMREQD + "'";
     Console.WriteLine(strMsg);
     
     rdr.Close();
     con.Close();
} catch (DB2Exception myException) { [...] }

Table 5 - DB2 UDB for Windows to DB2 UDB server (any platform) using IBM DB2 .NET Data Provider

Machine 1 ('myblue') DB2 UDB for Windows

Machine 2 ('aries') DB2 UDB server (any platform)

Commands to run on this machine:

Information you need to obtain from this machine, to perform the commands on machine 1

Part I: Configuring connectivity

Refer to part 1 of this article series for detailed connectivity setup instructions.

Part II: Compiling the programs that use the IBM DB2 .NET Data Provider

devenv /rebuild debug "dbConn_vb_adoNET_ibmdatadb2.sln"

For details see step-by-step guide 3 or step-by-step guide 4

Things to notice:

  • Refer to Table 8 when specifying .NET Data Providers
  • Use Table 9 as guide when specifying the ConnectionString property of a Connection object
  • Your code must reference the IBM DB2 .NET Data Provider type library, typically located at sqllib\bin\netf10
  • You do not need to catalog the DB2 database as an ODBC data source
  • If you specify the Server keyword/value pair in the ConnectionString and want to directly connect to the DB2 UDB server, the DB2 database does not need to be catalogued locally

To compile the sample programs, you need

  • DB2 UDB v8 Application Development Client with Fix Pack 2 or higher (Fix Pack 2 support for MS .NET framework v1.0) (Fix Pack 3 support for MS .NET framework v1.0 and v1.1)
  • Microsoft Data Access Components (MDAC) 2.7 or higher
  • Microsoft Visual Studio .NET (.NET framework v1.0) or Microsoft Visual Studio .NET 2003 (.NET framework v1.1)

The dbalias is used to connect to the database. When a dbalias is not provided in the Catalog command (per part I above), the dbalias is the same as the dbname.

Part III: Executing the program

dbConn_vb_adoNET_ibmdatadb2.exe sample db2admin mypsw

dbConn_cs_adoNET_ibmdatadb2.exe sample db2admin mypsw

* The sample programs were designed to take 3 arguments in this order: <database name> <userid> <password>

sample = Database name

db2admin = User id on the server

mypsw = Password on the server



Back to top


Scenario 4 - Connecting to a DB2 UDB database using the Microsoft OLE DB .NET Data Provider


Figure 4 - DB2 UDB for Windows application client to DB2 UDB (any platform) using the Microsoft OLE DB .NET Data Provider
Graphical representation of DB2 UDB for Windows application client to DB2 UDB (any platform) using the Microsoft OLE DB .NET Data Provider

Listing 7 and Listing 8 show how to connect to a DB2 database using the MS OLE DB .NET Data Provider and issue a simple select statement. You can find the sample applications dbConn_vb_adoNET_msoleddbnet.vb and dbConn_cs_adoNET_msoleddbnet.cs in the source code zip file here.


Listing 7: Visual Basic ADO.NET code snippet (Microsoft OLE DB .NET Data Provider)
			
Imports System.Data.OleDb
[...]
Dim cmd As OleDbCommand
Dim con As OleDbConnection
Dim rdr As OleDbDataReader
Dim v_IBMREQD As String
Try
    con = New OleDbConnection("DSN=SAMPLE;UID=db2admin;PWD=mypsw;" + _
                                      "Provider='IBMDADB2';")
    cmd = New OleDbCommand()
    cmd.Connection = con
    cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1"
    cmd.CommandTimeout = 20
    con.Open()

    rdr = cmd.ExecuteReader(CommandBehavior.SingleResult)
    While rdr.Read()
        v_IBMREQD = rdr.GetString(0)
    End While
    Console.WriteLine('IBMREQD' has a value of '" + v_IBMREQD + "'")

    rdr.Close()
    con.Close()
Catch myException As OleDbException
	[...]
End Try


Listing 8: C# ADO.NET code snippet (Microsoft OLE DB .NET Data Provider)
			
using System.Data.OleDb;
[...]
OleDbCommand cmd = null;
OleDbConnection con = null;
OleDbDataReader rdr = null;
int rowCount;
try
{
   con = new OleDbConnection("DSN=SAMPLE;UID=db2admin;PWD=mypsw;" + 
                                            "Provider='IBMDADB2';");
   cmd = new OleDbCommand();
   cmd.Connection = con;
   cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1";
   cmd.CommandTimeout = 20;
   con.Open();
   
   rdr = cmd.ExecuteReader(CommandBehavior.SingleResult);
   v_IBMREQD = "";
   while (rdr.Read() == true) {
         v_IBMREQD = rdr.GetString(0); }
   strMsg = "  Successful retrieval of record. Column" +
		    " 'IBMREQD' has a value of '" + v_IBMREQD + "'";
   Console.WriteLine(strMsg);

   rdr.Close();
   con.Close();
} catch (OleDbException myException) { [...] }

Table 6 - DB2 UDB for Windows to DB2 UDB server (any platform) using Microsoft OLE DB .NET Data Provider

Machine 1 ('myblue') DB2 UDB for Windows

Machine 2 ('aries') DB2 UDB server (any platform)

Commands to run on this machine:

Information you need to obtain from this machine, to perform the commands on machine 1

Part I: Configuring Connectivity

Refer to part 1 of this article series for detailed connectivity setup instructions.

Part II: Compiling the programs that use the IBM DB2 .NET Data Provider

devenv /rebuild debug "dbConn_vb_adoNET_ibmdatadb2.sln"

For details see step-by-step guide 3 or step-by-step guide 4

Things to notice:

  • Refer to Table 8 when specifying .NET Data Providers
  • Use Table 9 as guide when specifying the ConnectionString property of a Connection object
  • In the ConnectionString property, you must use the DSN keyword instead of the Database keyword.
  • Specify the Provider keyword/value pair in the ConnectionString property "Provider='IBMDADB2';"
  • You do not need to catalog the DB2 database as an ODBC data source
  • If you specify the Server keyword/value pair in the ConnectionString and want to directly connect to the DB2 UDB server, the DB2 database does not need to be catalogued locally

To compile the sample programs, you need

  • DB2 UDB v8 Application Development Client with Fix Pack 2 or higher (Fix Pack 2 support for MS .NET framework v1.0) (Fix Pack 3 support for MS .NET framework v1.0 and v1.1)
  • Microsoft Data Access Components (MDAC) 2.7 or higher
  • Microsoft Visual Studio .NET (.NET framework v1.0) or Microsoft Visual Studio .NET 2003 (.NET framework v1.1)

The dbalias is used to connect to the database. When a dbalias is not provided in the Catalog command (per part I above), the dbalias is the same as the dbname.

Part III: Executing the program

dbConn_vb_adoNET_msoleddbnet.exe sample db2admin mypsw

dbConn_cs_adoNET_msoleddbnet.exe sample db2admin mypsw

* The sample programs were designed to take 3 arguments in this order: <database name> <userid> <password>

sample = Database name

db2admin = User id on the server

mypsw = Password on the server



Back to top


Scenario 5 - Connecting to a DB2 UDB database using the Microsoft ODBC .NET Data Provider


Figure 5 - DB2 UDB for Windows application client to DB2 UDB (any platform) using the Microsoft ODBC .NET Data Provider
Graphical representation of DB2 UDB for Windows application client to DB2 UDB (any platform) using the Microsoft ODBC .NET Data Provider

Listing 9 and Listing 10 show how to connect to a DB2 database using the MS ODBC .NET Data Provider and issue a simple select statement. You can find the sample applications dbConn_vb_ado_msodbcnet.vb and dbConn_cs_ado_msodbcnet.cs in the source code zip file here.


Listing 9: Visual Basic ADO.NET code snippet (Microsoft ODBC .NET Data Provider)
			
Imports Microsoft.Data.Odbc
[...]
Dim cmd As OdbcCommand
Dim con As OdbcConnection
Dim rdr As OdbcDataReader
Dim v_IBMREQD As String
Try
    con = New OdbcConnection("DSN=SAMPLE;UID=db2admin;PWD=mypsw;" + _
                                   "Driver={IBM DB2 ODBC DRIVER};")
    cmd = New OdbcCommand()
    cmd.Connection = con
    cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1"
    cmd.CommandTimeout = 20
    con.Open()

    rdr = cmd.ExecuteReader(CommandBehavior.SingleResult)
    While rdr.Read()
        v_IBMREQD = rdr.GetString(0)
    End While
    Console.WriteLine('IBMREQD' has a value of '" + v_IBMREQD + "'")
    rdr.Close()
    con.Close()
Catch myException As OdbcException
	[...]
End Try


Listing 10: C# ADO.NET code snippet (Microsoft ODBC .NET Data Provider)
			
using Microsoft.Data.Odbc;
[...]
OdbcCommand cmd = null;
OdbcConnection con = null;
OdbcDataReader rdr = null;
int rowCount;
try
{
   con = new OdbcConnection("DSN=SAMPLE;UID=;PWD=;" + 
                                   "Driver={IBM DB2 ODBC DRIVER};");
   cmd = new OdbcCommand();
   cmd.Connection = con;
   cmd.CommandText = "SELECT * FROM SYSIBM.SYSDUMMY1";
   cmd.CommandTimeout = 20;
   con.Open();
   	
   rdr = cmd.ExecuteReader(CommandBehavior.SingleResult);
   while (rdr.Read() == true) {
         v_IBMREQD = rdr.GetString(0); }
   strMsg = "  Successful retrieval of record. Column" +
		    " 'IBMREQD' has a value of '" + v_IBMREQD + "'";
   Console.WriteLine(strMsg);
      
   rdr.Close();
   con.Close();
} catch (OdbcException myException) { [...] }

Table 7 - DB2 UDB for Windows to DB2 UDB server (any platform) using Microsoft ODBC .NET Data Provider

Machine 1 ('myblue') DB2 UDB for Windows

Machine 2 ('aries') DB2 UDB server (any platform)

Commands to run on this machine:

Information you need to obtain from this machine, to perform the commands on machine 1

Part I: Configuring connectivity

The DB2 database must cataloged as an ODBC data source. To catalog an ODBC data source:

db2 catalog system ODBC data source sample

or

db2 catalog user ODBC data source sample

To list ODBC data sources:

db2 list system ODBC data sources

or

db2 list user ODBC data sources

Refer to part 1 of this article series for detailed connectivity setup instructions and to part 4 for registering a database as an ODBC Data Source.

Part II: Compiling the programs that use the IBM DB2 .NET Data Provider

devenv /rebuild debug "dbConn_vb_adoNET_ibmdatadb2.sln"

For details see step-by-step guide 3 or step-by-step guide 4

Things to notice:

  • Refer to Table 8 when specifying .NET Data Providers
  • Use Table 9 as guide when specifying the ConnectionString property of a Connection object
  • Specify the Driver keyword/value pair in the ConnectionString property "Driver={IBM DB2 ODBC DRIVER};"
  • Specify the Provider keyword/value pair in the ConnectionString property "Provider='IBMDADB2';"
  • If using .NET framework v1.0, your code must reference the MS ODBC .NET Data Provider3 type library. On our system, it is located at c:\program files\Microsoft.NET\Odbc.Net\Microsoft.Data.Odbc.dll

To compile the sample programs, you need

  • DB2 UDB v8 Application Development Client with Fix Pack 2 or higher (Fix Pack 2 support for MS .NET framework v1.0) (Fix Pack 3 support for MS .NET framework v1.0 and v1.1)
  • Microsoft Data Access Components (MDAC) 2.7 or higher
  • MS ODBC .NET Data Provider3 (if using MS .NET framework v1.0)
  • Microsoft Visual Studio .NET (.NET framework v1.0) or Microsoft Visual Studio .NET 2003 (.NET framework v1.1)

The dbalias is used to connect to the database. When a dbalias is not provided in the Catalog command (per part I above), the dbalias is the same as the dbname.

Part III: Executing the program

dbConn_vb_adoNET_msodbcnet.exe sample db2admin mypsw

ddbConn_cs_adoNET_msodbcnet.exe sample db2admin mypsw

* The sample programs were designed to take 3 arguments in this order: <database name> <userid> <password>

sample = Database name

db2admin = User id on the server

mypsw = Password on the server

3MS ODBC .NET Data Provider is not part of the .NET Framework v1.0 and is available for download from Microsoft .NET Framework Download website.

Table 8 - ADO.NET Data Providers and their core objects

IBM DB2 .NET Data Provider

MS ODBC .NET Data Provider

MS OLE DB .NET Data Provider

Namespace

IBM.Data.DB2

Microsoft.Data.Odbc3 (.NET Framework v1.0)

or

System.Data.Odbc (.NET Framework v1.1)

System.Data.OleDb

Component

IBM.Data.DB2.dll

Microsoft.Data.Odbc.dll

or

System.Data.Odbc.dll

System.Data.dll

Connection Object

DB2Connection

OdbcConnection

OleDbConnection

Transaction Object

DB2Transaction

OdbcTransaction

OleDbTransaction

Command Object

DB2Command

OdbcCommand

OleDbCommand

DataReader

DB2DataReader

OdbcDataReader

OleDbDataReader

DataAdapter

DB2DataAdapter

OOdbcDataAdapter

OleDbDataAdapter

3MS ODBC .NET Data Provider is not part of the .NET Framework v1.0 and is available for download from Microsoft .NET Framework Download website.

Table 9 - ConnectionString keyword/value pairs specific for connecting to a DB2 UDB database

ConnectionString Keyword

Value

Database (also DSN4)

sample

UID

db2admin

PWD

mypsw

Server

aries or aries:50000 or 9.23.190.24:5000

(Specify when connecting directly to the DB2 UDB server)

Connection Timeout (also Connect Timeout) (also Timeout)

60 (Specified in seconds)

Pooling

true (Default)

or

false

Min Pool Size

0 (Default)

Max Pool Size

value is not assigned for no limit (Default)

Connection Reset

true

or

false

Connection Lifetime

15 (Specified in seconds) (Default)

Enlistt

true (Default)

or

false

Provider

IBMDADB2

(specify only when using MS OLE DB .NET Data Provider)

Driver

{IBM DB2 ODBC DRIVER}

(specify only when using MS ODBC .NET Data Provider)

4Use the Database keyword only when using the IBM DB2 .NET Data Provider, otherwise use the DSN keyword.

Table 10 - Solution to common errors

Error

Applicable to

Solution

1

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

  • MS OLE DB Provider for ODBC
  • MS ODBC .NET Data Provider

Make sure the ODBC data source is cataloged.

Make sure you specify the correct name for your database.

Test if the database has been catalogued correctly by connecting from the CLP:

db2 connect to <dbname> user <userid> using <psw>

2

Unhandled Exception: System.IO.FileNotFoundException: File or assembly name IBM.Data.DB2, or one of its dependencies, was not found.

IBM DB2 .NET Data Provider

Make sure you install DB2 UDB V8 Client or higher on your runtime system. If after installing 2 UDB V8 Client or higher you still get this error, (as a stop-gap measure) you can copy the IBM.Data.DB2.dll from \SQLLIB\BIN\netf10 or \SQLLIB\BIN\netf11 to your current working directory.

3

Unhandled Exception: System.IO.FileLoadException: The located assembly's manifest definition with name 'IBM.Data.DB2' does not match the assembly reference.

IBM DB2 .NET Data Provider

Make sure your runtime system has the same version of IBM DB2 .NET Data Provider as your development system.

4

An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'

MS OLE DB .NET Data Provider

Make sure you specify the Provider keyword in the ConnectionString as in 'Provider=IBMDADB2'

5

SQL1013N The database alias name or database name "" could not be found. SQLSTATE=42705

All except IBM DB2 .NET Data Provider

Make sure you specify the DSN keyword and not the Database keyword in the ConnectionString.

6

Invalid argument

IBM DB2 .NET Data Provider

Make sure you specify the Database keyword and not the DSN keyword in the ConnectionString.

7

Review the errors per part 4 of this article series.

All



Back to top


Registering the IBM DB2 Development Add-Ins for Visual Studio .NET

If Visual Studio .NET was installed prior to installing the DB2 UDB V8 Application Development Client (or higher), the IBM DB2 Development Add-Ins for Visual Studio .NET is automatically registered during the installation of DB2.

On the other hand, if you installed Visual Studio .NET after installing the DB2 UDB V8 Application Development Client (or higher) or if you modified your installation, you need to manually register the IBM DB2 Development Add-Ins for Visual Studio .NET.

This can be done in two ways:

1. From the Windows Start menu select:

Start -> Programs -> IBM DB2 -> Set-up Tools -> Register Visual Studio Add-Ins

2. From the DB2 Command Window, issue the following command:

db2nmpreg

You can also un-register the IBM DB2 Development Add-Ins for Visual Studio .NET.

From the DB2 Command Window, issue the following command:

db2nmpreg -u



Back to top


Step-by-step guide 1: Creating a Visual Basic ADO Application

The following steps create a Visual Basic ADO application using MS Visual Basic 6.

  1. Create a Visual Basic project
    1. On the File menu, select New Project
    2. On the New Project dialog, select Standard EXE project template. The new Visual Basic project will consist of one form (Form1) and the Project Explorer window should look similar to Figure 6.

    Figure 6 - Creating a new Visual Basic project
    Graphical representation of Creating a new Visual Basic project
  2. Copy and paste the Visual Basic sample application:
    1. On the Project menu, select Add Module.
    2. On the Add Module dialog, toggle the New tab and select Module. The Project Explorer window should show the new module (Module1) and should look similar to Figure 7.
    3. On the Project Explorer window, Right-Click on Form1 and select Remove Form1. Typically, you would use a form to provide a GUI to the user. For our sample applications, a pop-up message box will suffice.
    4. Copy and paste one of the Visual Basic ADO sample application (e.g., dbConn_vb_ado_ibmdadb2.bas) into Module1.

    Figure 7 - Adding the Visual Basic ADO sample application to the project
    Graphical representation of Adding the Visual Basic ADO sample application to the project
  3. Rename the project and set the project Startup Object:
    1. On the Project Explorer window, Right-click on Project1 and select Project1 Properties
    2. On the Project Properties dialog, under Startup Object select Sub Main and under Project Name specify a new project name, e.g. dbConn_vb_ado_ibmdadb2.

    Figure 8 - Setting the Startup Object of the project
    Graphical representation of Setting the Startup Object of the project
  4. Add reference to MS ADO type library:
    1. On the Project menu, select References
    2. On the References dialog, scroll-down and place select Microsoft ActiveX Data Objects X.X Library. The X.X stand for the version of Microsoft Data Access Components (MDAC) installed on your system. On our system as shown on Figure 9, we had installed MDAC 2.8 and chose Microsoft ActiveX Data Objects 2.8 Library. If the type library is not listed, click Browse and select the type library from the directory it was installed in. For example, on our system msado15.dll located at C:\Program Files\Common Files\System\ADO

    Figure 9 - Adding reference to the MS ADO type library
    Graphical representation of Adding reference to the MS ADO type library
  5. Create an executable from within the Visual Basic IDE:
    1. On the File menu, select Save Project. Specify the project directory and name for the module Module1 (e.g. dbConn_vb_ado_ibmdadb2.bas)
    2. On the File menu, select Make <projectname>.exe. This will generate an executable in the directory that you specified.

    Figure 10 - Creating an executable program for the project
    Graphical representation of creating an executable program for the project
  6. Create an executable from the command line.

    You can also create, from the command line, an executable for a Visual Basic project. At the command prompt, type:

    vb6 /m <projectname>.vbp

    e.g. vb6 /m dbConn_vb_ibmdadb2.vbp


    Figure 11 - Building the project from the command line
    Graphical representation of Building the project from the command line


Back to top


Step-by-step guide 2: Creating a Visual C++ ADO application

The following steps create a Visual C++ ADO application using MS Visual C++ 6.

  1. Create a Visual C++ project:
    1. On the File menu, select New
    2. On the New dialog, toggle the Projects tab and select Win32 Console Application project template. Specify the project name and directory under Project Name and Location respectively.
    3. On the Win32 Console Application dialog, select A simple application as the project template and click on the Finish button. The new VC++ project will consist of two C++ source files and one header file. The Project Workspace window should look similar to Figure 12.

    Figure 12 - Creating a new Visual C++ project
    Graphical representation of Creating a new Visual C++ project
  2. Copy and paste the VC++ sample application:
    1. Copy and paste one of the VC++ ADO sample applications (e.g. dbConn_vc_ado_ibmdadb2) into <projectname>.cpp file, as shown in Figure 13. Do not paste the into the precompiled header files: StdAfx.cpp, StdAfx.h.
    2. Copy and paste the ADO library headers declaration from the same sample application into the precompiled header file StdAfx.h, as shown in Figure 14.

    Figure 13 - Adding the Visual C++ ADO sample application to the project
    Graphical representation of Adding the Visual C++ ADO sample application to the project

    Figure 14 - Adding the sample application's ADO library headers to the precompiled header file
    Graphical representation of Adding the sample application's ADO library headers to the precompiled header file
  3. Create an executable from within the MS Visual C++ IDE:
    1. On the File menu, select Save All.
    2. On the Build menu, select Build <projectname>.exe. This will generate an executable file in the subdirectory Debug or Release under the project directory.

    Figure 15 - Creating an executable program for the project
    Graphical representation of Creating an executable program for the project
  4. Create an executable from the command line.

    You can also create, from the command line, an executable for a VC++ project. At the command prompt, type

    msdev <projectname>.dsp /make "<projectname> - Win32 Release" /rebuild

    e.g. msdev dbConn_vc_ado_ibmdadb2.dsp /make "dbConn_vc_ado_ibmdadb2 - Win32 Release" /rebuild


    Figure 16 - Building the project from the command line
    Graphical representation of Building the project from the command line


Back to top


Step-by-step guide 3: Creating a Visual Basic ADO.NET application

The following steps create a Visual Basic ADO.NET application using MS Visual Studio .NET.

  1. Create a Visual Basic .NET project:
    1. On the File menu, select New, then select Project
    2. On the New Project dialog, for Project Types select the Visual Basic Projects folder. For Templates, select Console Application project template. Specify the project name and directory under Name and Location respectively. The new VB .NET project will consist of two VB files (AssemblyInfo.vb and Module1.vb) and the Solution Explorer window should look similar to Figure 17.

    Figure 17 - Creating a new Visual Basic .NET project
    Graphical representation of Creating a new Visual Basic .NET project
  2. Copy and paste the VB .NET sample application.

    Copy and paste one of the VB ADO.NET sample applications (e.g. dbConn_vb_adoNET_ibmdatadb2.vb) into Module1.vb.


    Figure 18 - Adding the Visual Basic ADO.NET sample application to the project
    Graphical representation of Adding the Visual Basic ADO.NET sample application to the project
  3. Add references for the type libraries used in the sample application:
    1. On the Project menu, select Add Reference
    2. On the Add Reference dialog, toggle the .NET tab, scroll-down and select the IBM.Data.DB2.dll and Microsoft Visual Basic .NET Runtime components, and click on Select. Both components should now be listed under Selected Components. Click OK. If the component is not listed, click Browse and select the component from the directory it was installed in. For example, on our system
      • IBM.Data.DB2.dll located at F:\Program Files\IBM\SQLLIB\BIN\netf10
      • Microsoft.Data.Odbc.dll located at C:\Program Files\Microsoft.NET\Odbc.Net
    3. In the Solution Explorer window, Right-click on the Module1.vb file and select Rename. Specify a new file name (e.g. dbConn_vb_adoNET_ibmdatadb2.vb). The Solution Explorer window should look similar to Figure 19

    Figure 19 - Adding references to the type libraries
    Graphical representation of Adding references to the type libraries
  4. Set the project Startup object:
    1. In the Solution Explorer window, Right-click on the project (e.g. dbConn_vb_adoNET_ibmdadb2) and select Properties.
    2. On the Property Pages dialog, under the Common Properties folder and the General tab, select Sub Main as the Startup Object.

    Figure 20 - Setting the Startup Object of the project
    Graphical representation of Setting the Startup Object of the project
  5. Build the solution from within the MS Visual Studio .NET IDE:
    1. On the File menu, select Save All.
    2. On the Build menu, select Build Solution. This will generate an executable in the subdirectory bin under the project directory.

    Figure 21 - Creating an executable program for the project
    Graphical representation of Creating an executable program for the project
  6. Create an executable from the command line.

    You can also create, from the command line, an executable for a Visual Basic .NET project. At the command prompt, type

    devenv /rebuild debug "<projectname>.sln"

    e.g. devenv /rebuild debug "dbConn_vb_adoNET_ibmdatadb2.sln"


    Figure 22 - Building the project from the command line
    Graphical representation of Building the project from the command line
  7. Compile the Visual Basic .NET file from the command line.

    Instead of generating the executable from a Visual Basic .NET project, you can also create an executable for a Visual Basic .NET file from the command line. At the command prompt, type

    set tmpLibpath="F:\Program Files\IBM\SQLLIB\BIN\netf10" set tmpReference=IBM.Data.DB2.dll,Microsoft.VisualBasic.dll,System.dll,System.Data.dll vbc /libpath:%tmpLibpath% /reference:%tmpReference% /target:exe < filename>.vb /main:ConnectDb

    e.g. set tmpLibpath="F:\Program Files\IBM\SQLLIB\BIN\netf10" set tmpReference=IBM.Data.DB2.dll,Microsoft.VisualBasic.dll,System.dll,System.Data.dll vbc /libpath:%tmpLibpath% /reference:%tmpReference% /target:exe dbConn_vb_adoNET_ibmdatadb2.vb /main:ConnectDb


    Figure 23 - Compiling the Visual Basic .NET file from the command line
    Graphical representation of Compiling the Visual Basic .NET file from the command line


Back to top


Step-by-step guide 4: Creating a Visual C# ADO.NET application

The following steps create a Visual C# ADO.NET application using MS Studio .NET.

  1. Create a Visual Basic .NET project:
    1. On the File menu, select New, then select Project
    2. On the New Project dialog, for Project Types select the Visual C# Projects folder. For Templates, select Console Application project template. Specify the project name and directory under Name and Location respectively. The Solution Explorer window should look similar to Figure 24.

    Figure 24 - Creating a new Visual C# .NET project
    Graphical representation of Creating a new Visual C# .NET project
  2. Copy and paste the VC# .NET sample application.

    Copy and paste one of the VC# ADO.NET sample applications (e.g. dbConn_cs_adoNET_ibmdatadb2.cs) into Class1.cs file.


    Figure 25 - Adding the Visual C# ADO.NET sample application to the project
    Graphical representation of Adding the Visual C# ADO.NET sample application to the project
  3. Add references for the type libraries used in the sample application:
    1. In the Solution Explorer window, Right-click on the project (e.g. dbConn_cs_adoNET_ibmdadb2) and select Add Reference
    2. On the Add Reference dialog, toggle the .NET tab, scroll-down and select the IBM.Data.DB2.dll component and click on Select. Both components should now be listed under Selected Components. Click OK. If the component is not listed, click Browse and select the component from the directory it was installed in. For example, on our system
      • IBM.Data.DB2.dll located at F:\Program Files\IBM\SQLLIB\BIN\netf10
      • Microsoft.Data.Odbc.dll located at C:\Program Files\Microsoft.NET\Odbc.Net
    3. In the Solution Explorer window, Right-click on the Class1.cs file and select Rename. Specify a new file name (e.g. dbConn_cs_adoNET_ibmdatadb2.cs). The Solution Explorer window should look similar to Figure 26

    Figure 26 - Adding references to the type libraries
    Graphical representation of Adding references to the type libraries
  4. Set the project Startup object:
    1. In the Solution Explorer window, Right-click on the project (e.g. dbConn_cs_adoNET_ibmdadb2) and select Properties.
    2. On the Property Pages dialog, under the Common Properties folder and the General tab, select Sub Main as the Startup Object.

    Figure 27 - Setting the Startup Object of the project
    Graphical representation of Setting the Startup Object of the project
  5. Build the solution from within the MS Visual Studio .NET IDE:
    1. On the File menu, select Save All.
    2. On the Build menu, select Build Solution. This will generate an executable in the subdirectory bin\Debug or bin\Release under the project directory.

    Figure 28 - Creating an executable program for the project
    Graphical representation of Creating an executable program for the project
  6. Create an executable from the command line.

    You can also create, from the command line, an executable for a Visual Basic .NET project. At the command prompt, type

    devenv /rebuild debug "<projectname>.sln"

    e.g. devenv /rebuild debug "dbConn_cs_adoNET_ibmdatadb2.sln"


    Figure 29 - Building the project from the command line
    Graphical representation of Building the project from the command line
  7. Compile the Visual C# .NET file from the command line.

    Instead of generating the executable from a Visual C# .NET project, you can also create an executable for a Visual C# .NET file from the command line. At the command prompt, type

    set tmpReference="F:\Program Files\IBM\SQLLIB\BIN\netf10\IBM.Data.DB2.dll";System.dll;System.Data.dll csc /reference:%tmpReference% /target:exe <filename>.cs /main:ConnectDb

    e.g. set tmpReference="F:\Program Files\IBM\SQLLIB\BIN\netf10\IBM.Data.DB2.dll";System.dll;System.Data.dll csc /reference:%tmpReference% /target:exe dbConn_cs_adoNET_ibmdatadb2.cs /main:ConnectDb


    Figure 30 - Compiling the Visual C# .NET file from the command line
    Graphical representation of Compiling the Visual C# .NET file from the command line



Back to top


Downloads

NameSizeDownload method
Connectivity_ADO_ADONET.zip25.2 KB
ADO_ADONET_Results.pdf172.0 KB
SampleCode.zip25 KBFTP|HTTP
ADO_ADONET_Results.zip315 KB
Information about download methodsGet Adobe® Reader®


Resources



About the authors

Jalud Abdulmenan is a former IBM employee who left the company in 2002 to continue his professional studies. While at IBM, Jalud was responsible for Quality Assurance of two DB2 migration toolkits, and was instrumental in the development of the DB2 Scholars Support program, which helped promote DB2 UDB in universities. Currently, Jalud is in the process of setting up his own database consulting business.


Raul F. Chong is a database consultant from the IBM Toronto Laboratory and works primarily with IBM Business Partners. Raul has worked at IBM for six years, three years in DB2 Technical Support, and the other three as a consultant specializing in database application development and migrations from other RDBMS to DB2.




Rate this page


Please take a moment to complete this form to help us better serve you.



 


 


Not
useful
Extremely
useful
 


Share this....

digg Digg this story del.icio.us del.icio.us Slashdot Slashdot it!



Back to top