How to Query IBM iSeries DB2 Database with ADO.Net

How to connect ADO.Net to an IBM iSeries DB2 server or as an System I or AS400 and how to use parameters to create secure query strings.

By Tim Trott | C# ASP.Net MVC | January 29, 2010

You will need a copy of the IBM iSeries DB2 provider which is available from here: IBM iSeries DB2 for .Net 

Once you have downloaded and installed the package you will need to add a reference to IBM.Data.DB2.iSeries and add the following to your class:

C#
using IBM.Data.DB2.iSeries;

The IBM classes are similar to the standard .Net classes except for "iDB2" prefix.

The first thing to do is to create a connection string and a connection object. We then open the connection to the server.

This code is designed to illustrate the process for connection to DB2 server. It does not provide any error checking or exception handling.

C#
string conStr = "DataSource=127.0.0.1;UserID=USER;Password=PASS; DataCompression=True;";

iDB2Connection cn = new iDB2Connection(conStr);
cn.Open();

Next, we create a command and pass in a select query.

C#
iDB2Command cmd = cn.CreateCommand();
cmd.CommandText = "SELECT * FROM Products WHERE ProductCode = @ProdCode AND Language = @Lang";

You will notice that I have used the @ symbol in the command string. This denotes a SQL parameter and is a much safer way of building a command string than simply concatenating values to the string.

To use and populate SQL parameters you first need to derive parameters from the command string and then populate a collection with values.

C#
cmd.DeriveParameters();

cmd.Parameters["@ProdCode "].Value = "ABC123";
cmd.Parameters["@Lang"].Value = "EN";

Next, we execute the command and get the results back.

Using a DataReader with DB2

C#
iDB2DataReader reader = cmd.ExecuteReader();
C#
if (reader.HasRows)
{
  reader.Read();
  StringBuilder sb = new StringBuilder();

  for (int i = 0; i < reader.FieldCount; i++)
  {
    sb.AppendLine(reader[i].ToString().Trim());
  }
}

reader.Close();
cn.Close();

You will need to trim the return string as DB2 will return a padding string as defined on the physical file on the AS400. For example, if the field is defined as 50 characters, but only populated with 10, you will still get 50 characters back.

Using iDB2DataAdapter and DataSet with DB2

If you would prefer to retrieve all results at once, i.e. data binding to a control, you can use the iDB2DataAdapter and Microsoft DataSet classes.

C#
iDB2DataAdapter da = new iDB2DataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

GridView1.DataSource = ds;
GridView1.DataBind();

The iDB2DataAdapter also accepts as an overload a string for command and a string for connection, so a simple query could use the following code:

C#
string sql = "SELECT * FROM Products";
string con = "DataSource=127.0.0.1;UserID=USER;Password=PASS; DataCompression=True;";
iDB2DataAdapter da = new iDB2DataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds);
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 6 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. AW

    On Friday 28th of January 2022, Abdul Wasit said

    I am trying to establish a connection with AS400 using ADO.Net following the steps which are mentioned in this article. I am getting "DllNotFoundException: Unable to load DLL 'cwbdc.dll'". Can someone help me out to solve this issue?. Where I can find this 'cwbdc.dll?

    iDB2Connection connection = new iDB2Connection("DataSource=10.31.9.13;UserID=user;Password=password; DataCompression=True");

    1. Tim Trott

      On Thursday 3rd of February 2022, Tim Trott  Post Author replied

      You need to install IBM iSeries Access for Windows - https://www.ibm.com/docs/en/i/7.2?topic=packages-windows-application-package

  2. SU

    On Thursday 6th of February 2020, Suyog said

    string conStr = "DataSource=pub400.com;Uid=vjamdade;Pwd=vjamdade1; DataCompression=True;";
    iDB2Connection cn = new iDB2Connection(conStr);

    I have define connection string as above but i am getting error in connection string
    error is
    An unhandled exception of type 'IBM.Data.DB2.iSeries.iDB2InvalidConnectionStringException' occurred in IBM.Data.DB2.iSeries.dll
    Additional information: External component has thrown an exception.
    so kindly help me out to solve this issue

  3. ML

    On Tuesday 26th of September 2017, Marco Lozano said

    Where i can download the IBM DB2 iSeries package?

    1. Tim Trott

      On Tuesday 30th of November -0001, Tim Trott  Post Author replied

      You can download the .Net provider from IBM - https://www-03.ibm.com/systems/power/software/i/access/windows/dotnet.html

  4. MI

    On Thursday 19th of June 2014, Michael said

    Greetings,
    I am trying to run multiple statements in a iDB2DataAdapter and I do not know what separator to use for between SQL Query Statements.
    Using the System iNavigator "Run SQL Scripts functionality, you can run multiple query statements when you separate them with a semicolon ";"
    That does not work with the iDB2DataAdapter.
    If you terminate the first command with a ";", it returns the error:"SQL0104 Token ; was not valid. Valid tokens: ."
    Replacing the ";" with "END-OF-STATEMENT" returns the error:"SQL0199 Keyword END not expected. Valid tokens: FOR USE SKIP WAIT WITH FETCH ORDER UNION EXCEPT OPTIMIZE."
    Putting "BEGIN" and "END' around statements did not help.

    It can be hard to find information like this. If you have any suggestions, they would be appreciated. Thanks, Michael