DB2 UDB for iSeries .NET Provider - IBM

38
Table of Contents Introduction ......................................................................................................... 2 .NET Architecture and Data Access .................................................................. 3 .NET Glossary ..................................................................................................... 4 .NET Framework Components ........................................................................... 6 .NET versus J2EE ............................................................................................... 7 What is ADO.NET? .............................................................................................. 8 ADO.NET Object Model ...................................................................................... 9 .NET Provider Classes...................................................................................... 10 Providers contained in .NET Framework v1.1 ................................................ 11 Providers to access DB2 UDB for iSeries....................................................... 12 ADO.NET Providers supporting iSeries servers ............................................ 13 DB2 UDB for iSeries .NET Provider (Beta) notes ........................................... 15 What is in the Beta?.......................................................................................... 16 ADO.NET in a Connected Scenario ................................................................. 17 Connection Object ............................................................................................ 18 Command Object .............................................................................................. 19 Command Parameters ...................................................................................... 21 DataReader Object ............................................................................................ 22 DB2 UDB for iSeries .NET Provider in a connected scenario example ........ 24 ADO.NET in a Disconnected Scenario ............................................................ 25 How to create DataSets and DataTables? ...................................................... 27 Building DataSet programmatically ................................................................ 28 DataAdapter Object .......................................................................................... 29 DataAdapter Object Model ............................................................................... 30 DB2 UDB for iSeries .NET Provider in a disconnected scenario example...31 DB2 Application Development Technology Preview ..................................... 33 DB2 .NET Provider Example ............................................................................ 35 Choosing the .NET Provider for iSeries .......................................................... 36 Trademarks and Disclaimers ........................................................................... 38

Transcript of DB2 UDB for iSeries .NET Provider - IBM

Table of Contents Introduction.........................................................................................................2 .NET Architecture and Data Access ..................................................................3 .NET Glossary .....................................................................................................4 .NET Framework Components...........................................................................6 .NET versus J2EE ...............................................................................................7 What is ADO.NET?..............................................................................................8 ADO.NET Object Model ......................................................................................9 .NET Provider Classes......................................................................................10 Providers contained in .NET Framework v1.1 ................................................11 Providers to access DB2 UDB for iSeries.......................................................12 ADO.NET Providers supporting iSeries servers ............................................13 DB2 UDB for iSeries .NET Provider (Beta) notes ...........................................15 What is in the Beta?..........................................................................................16 ADO.NET in a Connected Scenario .................................................................17 Connection Object ............................................................................................18 Command Object ..............................................................................................19 Command Parameters......................................................................................21 DataReader Object............................................................................................22 DB2 UDB for iSeries .NET Provider in a connected scenario example........24 ADO.NET in a Disconnected Scenario ............................................................25 How to create DataSets and DataTables? ......................................................27 Building DataSet programmatically ................................................................28 DataAdapter Object ..........................................................................................29 DataAdapter Object Model ...............................................................................30 DB2 UDB for iSeries .NET Provider in a disconnected scenario example...31 DB2 Application Development Technology Preview .....................................33 DB2 .NET Provider Example ............................................................................35 Choosing the .NET Provider for iSeries..........................................................36 Trademarks and Disclaimers ...........................................................................38

Microsoft .NET Integration with DB2 UDB for iSeries

Jarek MiszczykSolutions Enablement, RochesterSpecial thanks extended to Brent Nelson, Rochester Development

January 2004

Introduction Welcome to this online course, Microsoft® .NET Integration with DB2® UDB for iSeries™. This course will discuss the basic concepts and components of the .NET Framework. It also talks about what ADO.NET is and its object model. We will also talk about the four providers that can be used to access DB2 UDB for iSeries from .NET applications. The course then moves on to talk about how to create DataSets and DataTables and the new tool, DB2 Universal Database4 Development Add-Ins for Visual Studio .Net. This course concludes with a discussion on how to choose the correct .NET Provider for your needs. We have lots of information to cover so let's get started.

.NET Architecture and Data Access

.NET is the latest Microsoft environment for running codeCode runs inside .NET execution runtime.NET runtime provides memory management, garbage collection, versioning, etc.

.NET Architecture and Data Access This online course discusses the technical aspects of Microsoft .NET integration with DB2 UDB for iSeries. However, before we can delve into the details we need to level set by discussing the basic concepts of .NET Framework. Specifically, we are going to focus on the new database access object model, namely ADO.NET. .NET is a language-neutral environment for writing programs that can easily interoperate. The .NET programs run inside the .NET execution runtime rather than on a particular hardware/operating system platform. .NET is also the collective name given to various software components built upon the .NET platform. The components that make up .NET environment are referred to as .NET Framework.

NET frameworkUnderlying plumbing for .NET applicationsCommon Language Runtime (CLR)Unified set of class libraries

CLRLanguage integration, security handling, memory/ thread/process management, exception handling

Managed codeCode that is compiled into a .NET assembly that can be executed in the context of .NET's CLR

ADO.NET.NET classes enabling access to databases

ASP.NET.NET classes to support development of Web-based applications and Web services

.NET Glossary

.NET Glossary The .NET Framework has two main components: the common language runtime and the unified .NET Framework class library. The common language runtime (CLR) is the foundation of the .NET Framework. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and security. In fact, the concept of code management is one of the corner stones of .NET architecture. Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code. The class library, the other main component of the .NET Framework, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as web forms and XML Web services. Typically, .NET applications use ADO.NET classes to access and manipulate database objects.

Similar to Java Virtual Machine (JVM)Object activation, security, code execution, and garbage collectionContains JIT for just-in-time compilationAvailable for Windows 98 and newerShipped with Windows 2003 Server64-bit version not yet availableCLI – Subset of CLR submitted to ECMA

Common Language Runtime (CLR)

Common Language Runtime (CLR) As mentioned, the common language runtime manages memory, thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime. .NET programs are not compiled directly into executable code but are compiled into an intermediary language known as Microsoft Intermediary Language (MSIL or IL). Later, at the program execution, the CLR loads the code into the runtime environment and a just-in-time compiler (JITer) compiles the IL into native executable code. This native code is then executed by the runtime's execution engine. Currently, CLR is available for Microsoft Windows® 98 and newer. Windows 2003 is shipped with a version of CLR. Note that currently, there is no 64-bit version of the runtime. In 2000, Microsoft submitted a subset of CLR specification to ECMA. This subset, known as Common Language Infrastructure (CLI), has become the ECMA-335 standard.

Web Services Web Forms Windows Forms

Data, Database, and XML Classes(ADO.NET, SQL, XSLT, XPath, XML, etc.)

Base Framework Classes(IO, data types, threading, security, etc.)

Common Language Runtime (CLR)(garbage collection, exceptions, type checking, JIT, etc.)

Operating System

.NET Framework Components

.NET Framework Components This graphic shows the major components of .NET architecture that have been discussed so far. Take a few minutes to review it.

.NET versus J2EE

Multiple languages (>25?)Easily call existing native code/componentsOne Intermediary Language (IL)One platform today (Windows)Dynamic web: ASP.NETDatabase access: ADO.NET

One languageJNI/System calls for native components One ILMultiple platforms (JVM)Dynamic web: JSPsDatabase access: JDBC SQL/J

.NET versus J2EE This graphic shows a head-to-head comparison of .NET and J2EE™. With J2EE implementation, IBM® has established architectural and product leadership on its server-oriented programming model, which is consistent, robust, cross-platform, and scalable, and provides integration of a rich IT environment. Business data and applications, transactions, security, reliable messaging, workload management, and system management are unique strengths that IBM provides for business logic and data-tier servers. IBM middleware runs cross platform. This is a key differentiator, and major weakness for .NET. Microsoft cannot run SQL Server, transaction management, etc. on OS/400, UNIX® or Linux.

What is ADO.NET?

Evolutionary improvement to Microsoft ActiveX® Data Objects (ADO) programming interfaceSet of classes that .NET applications can use to access data on a databaseBuilt for “disconnected” record setsData provider is used for connecting to a database, executing commands, and retrieving results

Database provider specific (DB2, SQL Server, Oracle, etc.)Providers implement vague interfaces in System.Data (IDbConnection, etc.)

Microsoft ships SQL Server, Oracle (with 1.1 Framework), and OleDb and ODBC bridge providers

What is ADO.NET? ADO .NET is an evolutionary improvement to Microsoft ActiveX® Data Objects (ADO) programming interface. ADO.NET consists of a set of classes that .NET applications can use to access data on a database. The data model for ADO.NET is primarily used with a disconnected dataset. ADO.NET will, for instance, get data from a data provider, manipulate the data in a disconnected manner, and then send the data back to the data provider to, in turn, update data on the database server. A .NET data provider is used for connecting to a database, executing commands, and retrieving results. The .NET Framework includes the SQL Server .NET Data Provider and the OLE DB .NET Data Provider. The SQL Server .NET Data Provider can only be used to access Microsoft SQL Server databases. Therefore, it is of no interest to DB2 UDB for iSeries users.

ADO.NET Object Model

Connection

Command

DataReader

DataAdapter

.NET Data Provider

DataSource

DataSet

XMLXML

DataGridDataGrid

CommandBuilder

ADO.NET Object Model The ADO.NET object model contains two major parts:

• DataSet classes • .NET provider classes

The DataSet classes are designed to store and manage data in a disconnected cache. The DataSet object does not depend on any underlying data source. The data provider classes are specific to a data source. In other words, the data providers are written for a specific data source and its classes can only be used with that data source. The data provider implements classes that allow you to connect to a data source, retrieve data, and perform updates.

.NET Provider Classes

Connection - for example, OleDbConnectionTransaction - for example, OleDbTransactionException - for example, OleDbExceptionError - for example, OleDbError

Command - for example, OleDbCommandParameter - for example, OleDbParameter

DataReader - for example, OleDbDataReaderDataAdapter - for example, OleDbDataAdapter

.NET Provider Classes There are four core classes that constitute the ADO.NET common object model:

• aConnection — Establishes connection to a given data source. For example, OleDbConnection class connects to a OLE DB compliant data source

• aCommand — Executes a command on a data source. For instance, the OleDbCommand class can execute a stored procedure or an SQL statement in a DB2 UDB for iSeries data source.

• aDataReader — Reads a forward-only, read-only set of records from a data source. The DataReader class is returned by calling the ExecuteReader method of the Command class.

• aDataAdapter — Uses aCommand objects to populate a DataSet and resolves updates with the data source.

Providers contained in .NET Framework v1.1

SQL ServerSystem.Data.SqlClient

OracleSystem.Data.OracleClient

Bridge to ODBC driversSystem.Data.Odbc

Bridge to OLE DB providersSystem.Data.OleDb

Providers contained in .NET Framework v1.1 The .NET Framework includes the SQL Server .NET Data Provider, the OLE DB .NET Data Provider, the ODBC .NET Data Provider, and the Oracle .NET Data Provider. The SQL Server .NET Data Provider can only be used to access Microsoft SQL Server databases. Therefore, it is of no interest to DB2 UDB for iSeries users. Similarly, the Oracle .NET Data Provider can only be used with Oracle databases. The OLE DB .NET Data Provider uses native OLE DB through COM interop module to enable data access. This provider is a "bridge" that handles calls from .NET into an "old" COM-style OLE DB Provider (IBMDA400 in the case of an iSeries server). The ODBC .NET provider directly accesses native ODBC drivers in the same way that the OLE DB .NET Data Provider accesses native OLE DB providers. Specifically, the ODBC .NET Data Provider can be used with the iSeries Access ODBC driver.

IBM DB2 UDB for iSeries .NET Provider (Beta)Available as of October 31, 2003!

DB2 UDB for .NET provider (technology preview)Managed .NET provider for DB2 UDB for LUWiSeries servers officially supported with the latest technology preview

Microsoft.Data.Odbc bridge to iSeries AccessSystem.Data.OleDb bridge to iSeries Access

Providers to access DB2 UDB for iSeries

Providers to access DB2 UDB for iSeries Currently, there are four providers that can be used to access DB2 UDB for iSeries from .NET applications:

• IBM.Data.DB2.iSeries — The new ADO.NET managed provider for iSeries Access for Windows

• DB2 UDB for .NET Provider — The DB2 for Linux, UNIX, and Windows (LUW) managed provider implemented by IBM software group

• Microsoft.Data.Odbc — The Microsoft supplied ODBC bridge provider using the iSeries Access for Windows ODBC driver for underlying database connectivity

• System.Data.OleDb — The Microsoft supplied OLEDB bridge provider using the iSeries Access OLEDB driver for underlying database connectivity

Let’s talk about these a little more.

ADO.NET Providers supporting iSeries servers

OleDbConnection

OleDbDataReaderOleDbCommand

OleDbDataAdapter

OLE DB .NET Data Provider

DataTable

DataSet

.NET Managed Applications

IBMDA400

CWBODBC

.NET

Man

aged

Cod

e

ADO.NET

TargetDB2

Database

iDB2Connection

iDB2DataReaderiDB2Command

iDB2DataAdapter

DB2 UDB for iSeries .NET provider

DB2Connection

DB2DataReaderDB2Command

DB2DataAdapter

DB2 for .NET Provider

DB2 Connect

OdbcConnection

OdbcDataReaderOdbcCommand

OdbcDataAdapter

ODBC .NET Data Provider

ADO.NET Providers supporting iSeries servers If you are using the .NET framework connecting to an iSeries host, choose the IBM.Data.DB2.iSeries database provider to support your PC and iSeries SQL application development. This managed provider will provide better performance than using the System.Data.OleDb provider to bridge to the iSeries Access OLE DB provider, or using the Microsoft.Data.Odbc provider to bridge to the iSeries Access ODBC driver. The OLE DB .NET Data Provider uses native OLE DB through COM interop module to enable data access. This provider is a "bridge" that handles calls from .NET into an "old" COM-style OLE DB Provider (IBMDA400 in the case of an iSeries server). The IBM development lab in Rochester, MN has recently enhanced the IBMDA400 provider so that it interacts with the OLE DB .NET Data Provider to facilitate access to the iSeries database. The OLE DB bridge involves jumping in and out of the .NET Framework environment for every interface call, because, from the .NET point-of-view, the IBMDA400 provider constitutes "unmanaged code." The unmanaged code simply means that it has been compiled directly into a binary executable. On the other hand, managed code is compiled into a .NET assembly that can be executed in the context of .NET's Common Language Runtime (CLR). In order for managed code to call

unmanaged code, marshaling of data must take place, and this can impact the overall performance. Therefore, Microsoft recommends that a managed provider is used in the .NET environment. Similar considerations apply when accessing iSeries through the ODBC .NET Data Provider.

DB2 UDB for iSeries .NET Provider (Beta) notes

iSeries Access .NET provider (Beta)Details available at:

ibm.com/servers/eserver/iseries/access/ Beta available October 31, 2003

Install requires the .NET framework be on PCWindows Server 2003 installs .NET framework by default

Same basic requirements as iSeries Access ODBC and OLE DB to useDatabase host server must be up and running

Limited support on pre-V5R2 servers

DB2 UDB for iSeries .NET Provider (Beta) notes The beta version of DB2 UDB for iSeries .NET Provider is sometimes called the iSeries Managed Provider. It supports a full set of .NET data types and SQL functionality to make it easy for applications to access and process data stored securely in databases on your iSeries server. The provider relies on services provided by the .NET Framework, therefore the framework needs to be installed on a PC prior to installing the iSeries Managed Provider. The provider communicates with a corresponding iSeries server job. This server job runs the SQL requests on behalf of the client. More precisely, when a client submits an SQL statement, the statement is passed to a server job that, in turn, calls the DB2 runtime to execute the statement. The results are then reformatted and marshaled to the client. The iSeries database access server jobs are called QZDASOINIT, and they run in the QUSRWRK subsystem. To take a full advantage of the provider's functionality, the iSeries server should be running OS/400® V5R2 or higher.

What is in the Beta?

SupportedSQL (INSERT,UPDATE, DELETE)Commitment ControlConnection PoolingSQL namingUnicodeTracingThreadsIASPs (multiple databases)CompressionStored procedure support

Not supportedLarge Objects (LOBs)System naming ( / )Package supportData linksUser Defined TypesRecord Level AccessCMD/PGM callData Queues

What is in the Beta? Take a minute to review this graphic. It provides a list of functions currently supported by the beta version of the DB2 UDB for iSeries .NET provider. It also lists features that are not available in this beta release. Now, let's have a closer look at the ADO.NET object model and the ways that ADO.NET providers can be used to manipulate DB2 UDB for iSeries data.

ADO.NET in a Connected Scenario

DataReader

Command

Connection

TargetDB2

Database

Resources are held on the server as long as the connection is openDataReader class provides forward-only, read-only access to data in a data source

ADO.NET in a Connected Scenario ADO.NET supports two main methods of accessing data: connected and disconnected. We will discuss this in more details over the next few charts. In the connected mode, a client application connects directly to the database. In this mode, clients interact with a database by connecting to a database, submitting commands to the database, and disconnecting. In a typical connected scenario, a DataReader object is used to read rows from tables stored in a database.

Connection Object

Connection string provides parameters required to establish a connectionProvider (OLE DB only)Data SourceInitial CatalogUser ID/Password

Opening and closing connection explicitlyOpen and Close methods on the Connection object

Opening and closing connection implicitlyData Adapters open and close connections automatically

Example:Dim dbConn As iDB2Connection = New _ iDB2Connection("DataSource=MyiSeries;" & _ "UserID=db2user;Password=db2pwd;DefaultCollection=SAMPLEDB")

Connection Object An ADO.NET connection object is used to establish a connection to a specific data source. For instance, the iDB2Connection object connects to DB2 UDB for iSeries. To successfully open an iSeries connection, security information, such as user ID and password, must be passed to the database. Typically, this information is provided by a ConnectionString property. In addition to the authentication information, the connection string may also specify other connection parameters such as Default Collection (schema), Default Isolation Level, Pooling, etc. Consult the DB2 UDB for iSeries .NET provider technical reference for a complete list of supported parameters. A connection can be opened and closed either implicitly, by calling methods on other objects that use the connection, or explicitly by invoking the Open and Close methods. The recommended approach is to open and close connections explicitly since this promotes more readable code and is more efficient.

Command Object

Reference to a SQL statement or stored procedureProperties

Connection, CommandType, CommandText,ParametersMethods

ExecuteScalar, ExecuteReader, ExecuteNonQuery

Example:Dim catCMD As iDB2Command = dbConn.CreateCommand()catCMD.CommandText = "SELECT Name FROM staff"dbConn.Open()Dim myReader As iDB2DataReader = catCMD.ExecuteReader()

Command Object A command object, such as iDB2Command, is used to execute action statements and submit queries. The properties of a command object are used to specify its execution context:

• Connection — Reference to a connection object used for communication with the database

• CommandType — Can be set to one the following values: Text, StoredProcedure, TableDirect

• CommandText — Contains the text of a SQL statement or the name of the stored procedure to be executed

• Parameters — Values required by Parametrized SQL statement or stored procedure

Depending on the type of the statement to be executed and expected results returned by the database, an application can call one of the following methods supported by a command object:

• ExecuteScalar — Returns an object that corresponds to the first column of the first row. This is useful for returning counters or other scalar values

• ExecuteReader — Returns a set of rows from the data store.

• ExecuteNonQuery — Updates the database or modifies its structure, returns the number of rows affected

Command Parameters

Parametrized SQL statements and stored procedures may require parameters

Command object has a collection of parametersCommand parameter objects allow you to set and retrieve parameters associated with a command objectProperties

ParameterName, DbType, Size, Direction

Example:...Dim cmStaff As iDB2Command = cniSeries.CreateCommand()cmStaff.CommandText = "SELECT NAME FROM STAFF WHERE (JOB = ?)"

Dim prmJob As New iDB2Parameter("JOB", iDB2DbType.iDB2VarChar, 5, "JOB")prmJob.Direction = System.Data.ParameterDirection.InputcmStaff.Parameters.Add(prmJob)cmStaff.Parameters("JOB").Value = "Mgr"

cniSeries.Open()

Command Parameters Parametrized SQL Statements and stored procedures use parameters to send and receive variable data from the server. The provider Command object, for instance iDB2Command, has a Parameters collection. This collection specifies a set of parameter objects (iDB2Parameter) that represent the value to be sent or received from the database. The properties of a Parameter can be used to specify its characteristics:

• DbType — Data type of the parameter. It depends on which provider is used. The iSeries Managed Provider supports data types such as iDB2Integer, iDB2VarChar, iDB2Decimal, etc.

• Size — Maximum size of the parameter data in bytes • Direction — Specifies the direction in which the data is passed. Possible

values include: • ParameterDirection.Input, • ParameterDirection.Output, • ParameterDirection.InputOutput, • ParameterDirection.ReturnValue

DataReader ObjectRead-only, forward-only, stream of rowsProperties

Item Gets the value of a column with a specific name or ordinal position

MethodsRead methodGetXxx methods

Return Common Language Specification (CLS) data types such as String, Int32, Double

GetValuesReturns an array of objects representing all column values for the current row

IsDbNull, CloseGetName, GetOrdinal, GetSchemaTable

Return metadata for the result setExample:Dim rdrStaff As iDB2DataReaderrdrStaff = cmStaff.ExecuteReader()Do While rdrStaff.Read() ListBox1.Items.Add(rdrStaff.GetString(0))LooprdrStaff.Close()

DataReader Object SQL statements and stored procedures often return a set of records. Managed providers retrieve these records through a DataReader object. The DataReader is a fast, forward-only cursor that iterates through a set of rows. A DataReader object can be created by invoking the ExecuteReader method on a Command object. The DataReader implements two interfaces:

• IDataReader — Provides a way to read a forward-only set of rows from a database.

• IDataRecord — Provides access to the columns within each row for a DataReader.

The DataReader provides a number of methods that can be used to manipulate the data in the result set:

• Read — Moves to the next row in the result set. The method returns false when there are no more records in the result set.

• Close — Closes the DataReader and releases the Connection object.

• GetXxx methods — The DataReader supports strongly typed methods such as GetInt16, GetDouble, GetDecimal that return CLS data types. Using the strongly typed data minimizes the conversion required to use the data in .NET applications. The DB2 UDB for iSeries .NET provider also supports methods that return DB2 specific data types such as GetiDB2Integer, GetiDB2Decimal, GetiDB2Double. The DB2 specific data types are defined in IBM.Data.DB2.iSeries namespace.

The DataReader also provides methods to retrieve the metadata information pertaining to the current result set.

DB2 UDB for iSeries .NET Provider exampleImports SystemImports System.Data[1] Imports IBM.Data.DB2.iSeriesImports Microsoft.VisualBasic

Public Module Module1 Public Sub Main() [2] Dim dbConn As iDB2Connection = New _ iDB2Connection("DataSource=myiSeries;" & _ "UserID=db2user;Password=db2pwd;DefaultCollection=SAMPLEDB") [3] Dim catCMD As iDB2Command = dbConn.CreateCommand() catCMD.CommandText = "SELECT Name FROM staff" dbConn.Open() [4] Dim myReader As iDB2DataReader = catCMD.ExecuteReader() Do While myReader.Read() Console.WriteLine(vbTab & "{0}", myReader.GetString(0)) Loop myReader.Close() dbConn.Close() End SubEnd Module

DB2 UDB for iSeries .NET Provider in a connected scenario example This graphic shows an example of the DB2 UDB for iSeries .NET Provider in a connected scenario. Here are a few key points: At [1], the necessary name space containing the iSeries provider implementation is imported. At [2], an iDB2Connection object is created to open a unique connection to the iSeries data source. The connection string passed to the iDB2Connection constructor contains properties typical for an iSeries provider. For example, the DefaultCollection property specifies the default database schema (library), in this case SAMPLEDB. The iDB2Command object instantiated at [3] is used for executing a query against the iSeries database. Since this sample is only required to read data and not to modify it, the iDB2DataReader is used at [4] rather than a DataSet. The DataReader requires very little memory and is quicker when compared to the DataSet.

ADO.NET in a Disconnected Scenario

DataSet

DataAdapter

Connection

TargetDB2

Database

Resources are not held on the server while the data is processedDataAdapter used to implicitly populate a DataSet and to update the central data store with changes made to the DataSet

ADO.NET in a Disconnected Scenario As mentioned earlier, ADO.NET supports two main methods of accessing data: connected and disconnected. In the disconnected mode, a DataAdapter object is used to retrieve data from the database and to store them in a DataSet object that constitutes a data cache. The data cached in a DataSet can be used by a .NET application without a need for multiple round-trips to the database. A DataAdapter can also implicitly update the central database with changes made to the DataSet.

DataSet Object

Corner stone of ADO.NET's disconnected architectureProvides a disconnected cache of data from any source

Structure follows the relational data modelLooks like in-memory databaseContains a collection of DataTables

DataTables contain DataColums and DataRowsDataTables can have primary key, foreign keys, relationships, and unique constraints

Supports computed columnsIs NOT a relational database though

Supports just a subset of SQL-like syntaxNo transactions or lockingCLR data types that are not compatible with SQL-99 standard

DataRow

DataColumn

Constraint

DataSet

DataTable DataTable …

PrimaryKey

DataRow …

…DataColumn

DataRelation

Property Property …

…DataRelation

DataSet Object The DataSet is a corner stone of the disconnected access method. It can cache data from any data source. The DataSet has been designed with relational concepts in mind. It can exchange data with database and XML providers. It is also possible to materialize and manipulate the DataSet programmatically. There are several ways in which the DataSet follows the relational data model. The DataSet contains a collection of tables. A DataTable represents one table of in-memory database. A DataTable contains a number of DataColumns. A DataColumn has a DataType property that determines what data can be stored in this DataColumn. A DataTable also contains a set of DataRow objects. A DataRow represents a row of data in a table. Additionally, a DataTable can have a primary key as well as foreign keys, relationships, and constraints. However, in spite of all the relation data model similarities, a DataSet is NOT a relational database. There several important characteristics of a relational database that are NOT supported by the DataSet:

• Supports a subset of SQL-like syntax only • No transactions or locking • CLR data types are not compatible with SQL-99 standard

How to create DataSets and DataTables?

ProgrammaticallyGraphical tools in Visual Studio .NETUsing DataAdapter and filling the DataSet from a relational data sourceLoading and storing DataSet contents using XML

How to create DataSets and DataTables? There are four methods that can be used to create DataSets and DataTables:

• Programmatically • Using the graphical tools in Visual Studio .NET • Using the DataAdapter and filling the DataSet from a relational data

source • Loading and storing the DataSet contents using XML

Let's focus for a while on how to instantiate and manipulate these objects with programming interfaces.

Building DataSet programmatically Add DataTable to DataSet programmatically

Dim dsSample As New DataSet("Sample")Dim dtStaff As DataTable = dsSample.Tables.Add("Staff")

Creating DataColumns programmatically

Dim colID As DataColumn = dtStaff.Columns.Add("ID", GetType(System.Int16))colID.AllowDBNull = False

Setting the PrimaryKey property of a DataTable

dtStaff.PrimaryKey = New DataColumn() {dtStaff.Columns("ID")}

Creating a new row

Dim drNewStaff As DataRow = dtStaff.NewRowdrNewStaff("ID") = 99drNewStaff("Name") = "Novak"dtStaff.Rows.Add(drNewStaff)

Saving a DataSet using XML

dsStaff.WriteXml("\My Documents\Staff.ds")

Building DataSet programmatically This graphic shows how to instantiate DataSet and DataTable objects using appropriate constructors. Then we use the Add method to add a DataColumn object to the newly created DataTable object. We also show how to specify a PrimaryKey constraint for a DataTable as well as how to add a row of data. One of the interesting features of a DataSet is its tight integration with XML. In this example, we show how to save the image of the in-memory data cache encapsulated by a DataSet to file on the local disk. There is also a corresponding ReadXml method to read the content of a stream file into a DataSet object.

DataAdapter Object

DataTable

DataSet

DataTable

DataAdapterDataAdapter

TargetDB2

Database

Update

Fill

Upd

ate

Fill

Bridge between a DataSet and a data sourceEncapsulates database connection and database commands used to retrieve and save dataExchanges data between a single DataTable and a single result set

DataAdapter Object A DataAdapter is a bridge that links DataSet and a data source. The DataAdapter encapsulates a database connection and a set of SQL commands that are used to retrieve the data from the database and update the database with the changes made to the DataSet. Note that a DataAdapter exchanges data with just one DataTable object. In other words, a DataSet typically has multiple DataAdapters associated with it.

DataAdapter Object Model

DataAdapterSELECT INSERTUPDATE DELETE

DataReader

Cammand CammandCammand Cammand

Connection

TargetDB2

Database

PropertiesSelectCommandUpdateCommandInsertCommandDeleteCommand

MethodsFillUpdate

DataAdapter Object Model A DataAdapter object contains four Command instances as member variables. It uses SelectCommand to retrieve data from the database to DataSet. It uses InsertCommand, UpdateCommand, and DeleteCommand to persist changes made to the DataSet in the database. There are two methods that can be used to move data between the DataSet and the database:

• Fill — Reads data from a data source and places them in a DataSet table. The Fill method uses the Select statement specified in the SelectCommand property.

• Update — Persists changes made to a DataSet's table in the corresponding data source. This method calls the relevant statements specified in InsertCommand, UpdateCommand, and DeleteCommand properties.

DB2 UDB for iSeries .NET Provider example Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles MyBase.Load Dim strConnectionString As String strConnectionString = "DataSource=MyiSeries;" & _ "UserID=db2user;Password=db2pwd;DefaultCollection=SAMPLEDB"[1]cniSeries = New iDB2Connection(strConnectionString) daStaff = New iDB2DataAdapter cmdDelete = New iDB2Command cmdInsert = New iDB2Command cmdSelect = New iDB2Command cmdUpdate = New iDB2Command dsSample = New DataSet [2]daStaff.DeleteCommand = cmdDelete daStaff.InsertCommand = cmdInsert daStaff.SelectCommand = cmdSelect daStaff.UpdateCommand = cmdUpdate ... cmdSelect.CommandText = "SELECT ID, NAME, DEPT, JOB, ""YEARS"", SALARY, COMM FROM STAFF" cmdSelect.Connection = cniSeries[3]cmdDelete.CommandText = "DELETE FROM STAFF WHERE (ID = ?)" cmdDelete.Connection = cniSeries cmdDelete.Parameters.Add(New iDB2Parameter("Original_ID", iDB2DbType.iDB2SmallInt, 0, _ System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), _ "ID", System.Data.DataRowVersion.Original, Nothing))[4]dsSample.Locale = New System.Globalization.CultureInfo("en-US") End Sub

DB2 UDB for iSeries .NET Provider in a disconnected scenario example This graphic shows an example of the DB2 UDB for iSeries .NET Provider in a disconnected scenario. Here are a few key points: At [1], an iDB2Connection object is created to open a database connection to the iSeries server. NOTE: that this time, the connection string contains parameters that are typical for DB2 UDB for iSeries .NET provider. At [2], an iDB2DataAdapter object is set up. A DataAdapter is used to exchange the data between a data source and a DataSet object. This means that the data is read from a database into a DataSet, and then the changed data is written from the DataSet back to the database. At [3], the DataAdapter is used to specify the delete statement. The delete request is then sent to the DataSet that in turn uses the database connection to propagate the change to the database server. At [4], a corresponding DataSet object is set up. The DataSet class is the central point of the ADO.NET's disconnected architecture. It holds a copy of the data retrieved by the DataAdapter. The code for the insert and update commands is not shown for clarity.

.NET Framework Integration with DB2 UDB

IBM DB2 Development Add-Ins for Visual Studio.NetAvailable as part of DB2 UDB and DB2 Connect 8.1.3 (Fix Pack 3)

The key features include: Managed provider for coding server-side objects using the ADO.Net programming model Solution explorer for building DB2 server-side objects Server explorer for gaining access to DB2 server-side objects from any tier of an application SQL editor for using the Visual Studio .NET editor to edit and view DB2 scripts Output views for showing the results of compiling or testing DB2 script files and server objects

DB2 UDB for iSeries support:Managed provider supports iSeries servers

DB2 Connect connection to iSeries is requiredThe Visual Studio .Net Add-Ins in Fix Pack 3 do not support iSeries servers

.NET Framework Integration with DB2 UDB The IBM DB2 Universal Database™ Development Add-Ins for Visual Studio .Net is a set of tightly integrated application development and administration tools specifically designed for DB2 UDB. The DB2 database project template lets you use scripts for developing server-side objects, including stored procedures, user-defined functions (UDFs), tables, views, indexes, and so on. The DB2 Development Add-Ins for Visual Studio .Net are available as part of DB2 UDB and DB2 Connect™ 8.1.3 (Fix Pack 3). The Add-Ins contain the DB2 .NET Managed Provider that can be used to connect to the iSeries database through an existing DB2 Connect connection. However, the visual plug-ins such as server explorer or SQL Editor do not support the iSeries server. The full support of iSeries servers is planned for the future release of DB2 UDB for LUW. The preview of the future enhancements is currently available through the DB2 Application Development Technology Preview program. The next graphic has more details on this Technology Preview.

Improved DB2 .NET Data Provider with better performance and support for DB2 UDB for iSeries serversEnhanced DB2 add-ins for Microsoft Visual Studio. NET Support for building and deploying stored procedures and user defined functions using Visual Basic .NET, C# and other CLR programming languages (DB2 UDB for LUW only)Support for creating and deploying SQL/PL stored procedures and functions To participate in this technology preview program, visit: https://www6.software.ibm.com/reg/dm/dm-adtpapp-i

DB2 Application Development Technology Preview!

DB2 Application Development Technology Preview IBM is providing a preview of technologies designed to enhance productivity of the .NET and Java™ application programmers. This technology preview is providing a significant new function in the areas of integration with Visual Studio .NET, improved performance for .NET and Java applications, significant enhancements for stored procedure and user defined function developers, and a preview of industry leading data modeling solutions. This technology preview also broadens the scope of data sources that .NET programmers can access with the introduction of fast .NET connectivity and much simplified programming facilities for building applications that work with DB2 UDB for iSeries servers. Specifically, this technology preview delivers these functions:

• Improved DB2 .NET Data Provider with better performance and support for DB2 UDB for iSeries servers

• Enhanced DB2 add-ins for Microsoft Visual Studio. NET with many functions that greatly improve programmer productivity and new support for the DB2 UDB for iSeries servers

• Support for building and deploying stored procedures and user defined functions using Visual Basic .NET, C#, and other CLR compliant programming languages

• Support for creating and deploying SQL/PL stored procedures and functions without a need for a C compiler

• New JDBC Type 4 driver with support for JDBC 3.0 APIs • Rational Rose XDE Developer tools for both Java and .NET software

developers and database designers to assist with software design and development as well as with logical and physical database design and generation

To participate in this technology preview program, please visit: https://www6.software.ibm.com/reg/dm/dm-adtpapp-i

DB2 .Net Provider Example Imports IBM.Data.DB2 ... Dim strConnectionString As String strConnectionString = "database=MYiSERIES;user Id=db2user;password=db2user;" [1]db2cniSeries = New IBM.Data.DB2.DB2Connection(strConnectionString) db2daDummy = New IBM.Data.DB2.DB2DataAdapter db2cmdSelect = New IBM.Data.DB2.DB2Command db2cmdDelete = New IBM.Data.DB2.DB2Command[2]daDummy.DeleteCommand = db2cmdDelete daDummy.SelectCommand = db2cmdSelect ... db2cmdSelect.CommandText = "SELECT ID, COL2 FROM DUMMY" db2cmdSelect.Connection = db2cniSeries[3]db2cmdDelete.CommandText = "DELETE FROM DUMMY WHERE (ID = ?) " db2cmdDelete.Connection = db2cniSeries db2cmdDelete.Parameters.Add(New IBM.Data.DB2.DB2Parameter("Original_ID", _ IBM.Data.DB2.DB2Type.SmallInt, 1, System.Data.ParameterDirection.Input, _ False, CType(0, Byte), CType(0, Byte), "ID", _ System.Data.DataRowVersion.Original, Nothing))[4]dsSample.Locale = New System.Globalization.CultureInfo("en-US") End Sub

DB2 .NET Provider Example This graphic shows an example of the DB2.NET. Here are a few key points: At [1], a DB2Connection object is created to open a database connection to the iSeries server. The DRDA protocol is used to connect to the iSeries through a DB2 Connect gateway. The Remote Database must be previously registered in DB2 Connect. The Configuration Assistant (ca) can be utilized for that purpose. At [2], a DB2DataAdapter object is set up. A DataAdapter is used to exchange the data between a data source and a DataSet object. At [3], the DataAdapter is used to specify the delete statement. The delete request is then sent to the DataSet that, in turn, uses the database connection to propagate the change to the database server. At [4], a corresponding DataSet object is set up. The code for the insert and update commands is not shown for clarity.

Choosing the .NET Provider for iSeries

DB2 UDB for iSeries .NET provider is the best choice to access iSeries servers

Optimized for iSeries access - best overall performanceSupports a range of iSeries specific properties

DB2 UDB (LUW) .NET Managed ProviderConsidered when access to different DB2 platform is requiredRequires a DRDA (DB2 Connect) connection to iSeries serversNot as efficient as DB2 UDB for iSeries .NET provider

ODBC .NET Data Provider and OLE DB .NET data providerLess efficient than DB2 UDB for iSeries .NET providerConsider only when access to heterogeneous databases is required or when accessing an older version of OS/400

Choosing the .NET Provider for iSeries Choosing the appropriate .NET data provider for your application depends on your environment. If you plan to access only iSeries databases, the DB2 UDB for iSeries .NET provider should be your choice. This managed provider will provide better performance than using the System.Data.OleDb provider to bridge to the iSeries Access OLE DB provider, or using the Microsoft.Data.Odbc provider to bridge to the iSeries Access ODBC driver. Consider the DB2 UDB for LUW provider if you need to access different DB2 UDB platforms such as DB2 UDB for Windows or DB2 UDB for z/OS® in addition to iSeries or if you wish to take advantage of the GUI Add-Ins provided with the DB2 Application Development Technology Preview discussed on the previous graphic.

Summary

Covered the most important aspects of Microsoft .NET intergrations with DB2 UDB for iSeries

AOD.NET object model and source code samples.NET data provider Four .NET data providers for DB2 UDB for iSeries

Large number of source code snippets provide clarity for programming techniques required for efficient DB2 UDB for iSeries access

Conclusion This online course covered the most important aspects of Microsoft .NET integration with DB2 UDB for iSeries. The ADO.NET object model was discussed and illustrated with source code samples. The .NET data provider concept was explained and then, the four .NET data providers available for DB2 UDB for iSeries were discussed in a greater detail. A large number of source code snippets were provided to clarify the programming techniques required for efficient DB2 UDB for iSeries access.

Trademarks and DisclaimersIBM, eServer, iSeries, DB2, DB2 Connect, OS/400 and DB2 Universal Database are trademarks or registered trademarks of International Business Machines Corporation.

Java, J2EE and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

Microsoft, Windows, Microsoft ActiveX, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.

IBM makes no commitment to make available any products referred to herein.

All other registered trademarks and trademarks are properties of their respective owners.

References in this publication to IBM products or services do not imply that IBM intends to make them available in every country in which IBM operates.

This material contains IBM copyrighted sample programming source code ("Sample Code"). IBM grants you a nonexclusive license to compile, link, execute, display, reproduce, distribute and prepare derivative works of this Sample Code. The Sample Code has not been thoroughly tested under all conditions. IBM, therefore, does not guarantee or imply its reliability, serviceability, or function. IBM provides no program services for the Sample Code. All Sample Code contained herein is provided to you "AS IS" without any warranties of any kind.

Trademarks and Disclaimers