StarQuest Technical Documents

How To Execute a DB2 Query from a Visual Basic .NET Application Using StarSQL

Last Update: 26 June 2008
Product: StarSQL
Version: 5.x
Article ID: SQV00SQ010

Abstract

This document describes how to execute a DB2 query from a Visual Basic .NET application using the StarSQL software and the Microsoft ODBC.NET Data Provider.

Solution

This solution uses the STAFF table provided with the DB2 UDB Sample tables. Contact IBM to obtain a copy of this sample table. The sample code for adding a command button in step 7 is excerpted from Microsoft Knowledge Base Article 310985.

  1. If you have not already done so, download and install the ODBC .NET Managed Provider from the Microsoft Download Center.
  2. Start Visual Studio .NET and create a new Visual Basic .NET Windows Application.
  3. On the Project menu, click Add Reference. On the .NET tab, double-click Microsoft.Data.ODBC.dll to add a reference to the Microsoft.Data.ODBC namespace. Click OK.
  4. Switch to Code view (press F7), and add the following code immediately before the Public Class Form1 code:

Imports System.Data
Imports Microsoft.Data.ODBC

  1. Switch back to Design View. Add a Button control to Form1 and label it StarSQL.
  2. Double-click the StarSQL command button to switch to the code window for the button Click event.
  3. Paste the following code in the Click event procedure, changing the connection string as appropriate to supply a valid StarSQL DSN and DB2 userid and password.  Also modify the SQL statement to provide the appropriate schema for the STAFF table, or set the mystring object to any simple SELECT statement that returns a result set.

Dim cn As OdbcConnection
Try

cn = New OdbcConnection("DSN=STARSQL_DSN;UID=DB2USER;PWD=PASSWORD;")

Dim mystring As String = "SELECT NAME FROM <SCHEMA>.STAFF"

Dim cmd As OdbcCommand = New OdbcCommand(mystring, cn)

cn.Open()

Dim dr As OdbcDataReader = cmd.ExecuteReader()

While dr.Read

Console.WriteLine(dr.GetString(0))

End While

dr.Close()

Catch o As OdbcException

MsgBox(o.Message.ToString)

Finally

cn.Close()

End Try

  1. Run the project.

The code executes the DB2 query and displays the result set.  You should see the NAME column values of the STAFF table in the Output window.


DISCLAIMER

The information in technical documents comes without any warranty. The author(s) or distributor(s) will not accept responsibility for any damage incurred directly or indirectly through use of the information contained in these documents. The information in technical documents may be gathered from various sources, including IBM, Microsoft, and other organizations.