Monday, September 19, 2011

How to Connect to DB2 with .NET

First you must install either the IBM Data Server Client or the IBM Data Server Runtime Client. The IBM Data Server Client has some additional developer tools but they are optional, so if you are searching for the most lightweight install then choose the IBM Data Server Runtime Client.

Next you must determine if a license is required. If you are connecting through a DB2 Connect Gateway then a license is not required, but if you are connecting directly to the DB2 Database then a license must be activated on the client computer.

To activate the license you must locate the db2conpe.lic file on your DB2 / DB2 Connect install CD. Once you have located this file, copy it to the client computer in the following directory: "C:\Program Files\IBM\SQLLIB\BIN" (location where your DB2 Client was installed). Now open a command prompt and change the directory to "C:\Program Files\IBM\SQLLIB\BIN" and execute this command: "db2licm -a db2conpe.lic". It should say that your license was successfully activated. You can verify this by typing "db2licm -l".

Now you are ready to start programming. Open Visual Studio and start a new console project. Before you start add a new reference (Project -> Add Reference) and browse to "C:\Program Files\IBM\SQLLIB\BIN\netf20\IBM.Data.DB2.dll".

Now copy and paste this code into your class file:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using IBM.Data.DB2;

namespace ConnectToDB2
{
    class Program
    {
        static void Main(string[] args)
        {
            string sql = "SELECT * FROM SYSIBM.SYSDUMMY1";
            DB2Connection con = new DB2Connection("Database=<DATABASE>;UserID=<USER_ID>;Password=<PASSWORD>;Server=<SERVER>:<PORT>");
            con.Open();

            DB2Command cmd = new DB2Command(sql, con);
            DB2DataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine(reader.GetString(0));
            }
        }
    }
}

Obviously replace the placeholders in the connection string with valid values.

2 comments:

  1. Now why in the world would you ever **want** to connect to DB2 :).

    Looks like your basic .net DBConnection - I had a fun time working with ODP.NET recently. Using generic insert statements (not using any bind variables) I would pump out about 30 inserts in a second and then it would hang for anywhere from 15 - 120 seconds!
    I changed everything to use stored procedures and bind variables to resolve the latency but...

    ReplyDelete
  2. Yes I'm not sure why you would want to connect to DB2 either.

    I had to use DB2 a couple times when I worked at Forethought. Definitely prefer Oracle, SQL Server, or MySQL.

    ReplyDelete