Microsoft KB Archive/815629

= HOW TO: Retrieve the Identity Value While Inserting Records into Access Database By Using Visual Basic .NET =

Article ID: 815629

Article Last Modified on 5/12/2007

-

APPLIES TO


 * Microsoft ADO.NET 1.0
 * Microsoft ADO.NET 1.1
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft Visual Basic .NET 2003 Standard Edition

-





For a Microsoft Visual C# .NET version of this article, see 816112.

IN THIS TASK

 * SUMMARY
 * Connect to the Access Database
 * Trap the Identity Column Value
 * Complete Code Listing
 * REFERENCES



SUMMARY
This step-by-step article discusses how to retrieve the identity column value from an Access database.

Retrieving the Identity value from a Jet database is different from that of SQL Server, because a Jet database does not support multi-statement batch commands. The Jet OLE DB version 4.0 provider supports the SELECT @@Identity query that allows you to retrieve the value of the auto-increment field that is generated on your connection. To run the SELECT @@Identity query, it is recommended that you use another OleDbCommand object. This article describes how to use a second OleDbCommand to retrieve the Identity column value.

Note: This feature works only with Microsoft Jet OLEDB 4.0 databases. The earlier versions of Microsoft Jet OLEDB do not support this feature.

back to the top



Connect to the Access Database
To connect to the Access Database and create a table with the Identity column, follow these steps:  Start Microsoft Visual Studio .NET 2002. On the File menu, point to New, and then click Project. Under Project Types, click Visual Basic Projects. Under Templates section, click Console Application. By default, Module1.vb is created. Name the project MyJetApplication and then click OK.  Replace the existing code with the following code: Imports System Imports System.Data Imports System.Data.OleDb

Module Module1

Sub Main

' Open Connection Dim cnJetDB As OleDbConnection = New OleDbConnection(&quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase&quot;) cnJetDB.Open

' If the test table does not exist, create the Table. Dim strSQL As String strSQL = &quot;CREATE TABLE AutoIncrementTest &quot; & _ &quot;(ID int identity, Description varchar(40), &quot; & _              &quot;CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID))&quot;

' Command for creating Table. Dim cmdJetDB As New OleDbCommand(strSQL, cnJetDB) cmdJetDB.ExecuteNonQuery

' Create a DataAdaptor With Insert Command For inserting records Dim oleDa As New OleDbDataAdapter(&quot;Select * from AutoIncrementTest&quot;, cnJetDB)

' Command to Insert Records. Dim cmdInsert As New OleDbCommand cmdInsert.CommandText = &quot;INSERT INTO AutoIncrementTest (Description) VALUES (?)&quot; cmdInsert.Connection = cnJetDB cmdInsert.Parameters.Add(New OleDbParameter(&quot;Description&quot;, OleDbType.VarChar, 40, &quot;Description&quot;)) oleDa.InsertCommand = cmdInsert

' Create a DataTable Dim dtTest As New DataTable oleDa.Fill(dtTest)

Dim drTest As DataRow

' Add Rows to the Table drTest = dtTest.NewRow drTest(&quot;Description&quot;) = &quot;This is a Test Row 1&quot; dtTest.Rows.Add(drTest)

drTest = dtTest.NewRow drTest(&quot;Description&quot;) = &quot;This is a Test Row 2&quot; dtTest.Rows.Add(drTest) End Sub

End Module  Modify the Data Source name in the connection string to point to your Access Database.</li></ol>

back to the top

Trap the Identity Column Value
To summarize the steps, in the RowUpdated event of the DataAdapter, you can trap the identity column value that is generated for a column of a Table in an Access Database. In the RowUpdated event, you will run the SELECT @@IDENTITY query by using another Command object, and then you will assign the value that is returned by the query to the Identity column. Lastly, call the AcceptChanges method of the DataRow object to accept the column value.

The trap the identity column value, follow these steps: <ol>  Add the following code before the Main method to create a second OleDbCommand object for the SELECT @@IDENTITY query: ' Create OleDbCommand for SELECT @@IDENTITY statement Private cmdGetIdentity As OleDbCommand </li>  Append the following code to the Main method for creating a new instance of OleDbCommand class: ' Create another command to get IDENTITY value. cmdGetIdentity = New OleDbCommand cmdGetIdentity.CommandText = &quot;SELECT @@IDENTITY&quot; cmdGetIdentity.Connection = cnJetDB </li>  Append the following code to the Main method for handling the RowUpdated event: ' Delegate for handling RowUpdated event. AddHandler oleDa.RowUpdated, AddressOf HandleRowUpdated </li>  Append the following code to the Main method for updating the data. The RowUpdated event is raised after calling the Update method. ' Update the Data oleDa.Update(dtTest) </li>  Append the following code to the Main method to drop the AutoIncrementTest table and release the resources: ' Drop the table cmdJetDB.CommandText = &quot;DROP TABLE AutoIncrementTest&quot; cmdJetDB.ExecuteNonQuery

' Release the resources. cmdGetIdentity.Dispose cmdGetIdentity = Nothing cmdInsert.Dispose cmdInsert = Nothing cmdJetDB.Dispose cmdJetDB = Nothing cnJetDB.Close cnJetDB.Dispose cnJetDB = Nothing </li>  Add the following RowUpdated event handler code to Module1: ' Event handler for RowUpdated event. Private Sub HandleRowUpdated(ByVal sender As Object, ByVal e As OleDbRowUpdatedEventArgs) If e.Status = UpdateStatus.Continue AndAlso e.StatementType = StatementType.Insert Then ' Get the Identity column value e.Row(&quot;ID&quot;) = Int32.Parse(cmdGetIdentity.ExecuteScalar.ToString) Debug.WriteLine(e.Row(&quot;ID&quot;)) e.Row.AcceptChanges End If  End Sub </li> On the Debug menu, click Start to run the application. Identity column values are displayed in the Output window.</li></ol>

back to the top

Complete Code Listing
Imports System Imports System.Data Imports System.Data.OleDb

Module Module1

' Create OleDbCommand for SELECT @@IDENTITY statement Private cmdGetIdentity As OleDbCommand

Sub Main

' Open Connection Dim cnJetDB As OleDbConnection = New OleDbConnection(&quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase&quot;) cnJetDB.Open

' If the test table does not exist then create the Table Dim strSQL As String strSQL = &quot;CREATE TABLE AutoIncrementTest &quot; & _ &quot;(ID int identity, Description varchar(40), &quot; & _              &quot;CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID))&quot;

' Command for Creating Table Dim cmdJetDB As New OleDbCommand(strSQL, cnJetDB) cmdJetDB.ExecuteNonQuery

' Create a DataAdaptor With Insert Command For inserting records Dim oleDa As New OleDbDataAdapter(&quot;Select * from AutoIncrementTest&quot;, cnJetDB)

' Command to Insert Records Dim cmdInsert As New OleDbCommand cmdInsert.CommandText = &quot;INSERT INTO AutoIncrementTest (Description) VALUES (?)&quot; cmdInsert.Connection = cnJetDB cmdInsert.Parameters.Add(New OleDbParameter(&quot;Description&quot;, OleDbType.VarChar, 40, &quot;Description&quot;)) oleDa.InsertCommand = cmdInsert

' Create a DataTable Dim dtTest As New DataTable oleDa.Fill(dtTest)

Dim drTest As DataRow

' Add Rows to the Table drTest = dtTest.NewRow drTest(&quot;Description&quot;) = &quot;This is a Test Row 1&quot; dtTest.Rows.Add(drTest)

drTest = dtTest.NewRow drTest(&quot;Description&quot;) = &quot;This is a Test Row 2&quot; dtTest.Rows.Add(drTest)

' Create another Command to get IDENTITY Value cmdGetIdentity = New OleDbCommand cmdGetIdentity.CommandText = &quot;SELECT @@IDENTITY&quot; cmdGetIdentity.Connection = cnJetDB

' Delegate for Handling RowUpdated event AddHandler oleDa.RowUpdated, AddressOf HandleRowUpdated

' Update the Data oleDa.Update(dtTest)

' Drop the table cmdJetDB.CommandText = &quot;DROP TABLE AutoIncrementTest&quot; cmdJetDB.ExecuteNonQuery

' Release the Resources cmdGetIdentity.Dispose cmdGetIdentity = Nothing cmdInsert.Dispose cmdInsert = Nothing cmdJetDB.Dispose cmdJetDB = Nothing cnJetDB.Close cnJetDB.Dispose cnJetDB = Nothing End Sub

' Event Handler for RowUpdated Event Private Sub HandleRowUpdated(ByVal sender As Object, ByVal e As OleDbRowUpdatedEventArgs) If e.Status = UpdateStatus.Continue AndAlso e.StatementType = StatementType.Insert Then ' Get the Identity column value e.Row(&quot;ID&quot;) = Int32.Parse(cmdGetIdentity.ExecuteScalar.ToString) Debug.WriteLine(e.Row(&quot;ID&quot;)) e.Row.AcceptChanges End If  End Sub End Module

<div class="references_section">