HOWTO: 通过使用 VisualBasic.NET 将记录插入 Access 数据库时检索标识值
<script type="text/javascript">function loadTOCNode(){}</script>
文章编号 | : | 815629 |
最后修改 | : | 2007年5月12日 |
修订 | : | 3.1 |
本页
<script type="text/javascript"> var sectionFilter = "type != 'notice' && type != 'securedata' && type != 'querywords'"; var tocArrow = "/library/images/support/kbgraphics/public/en-us/downarrow.gif"; var depthLimit = 10; var depth3Limit = 10; var depth4Limit = 5; var depth5Limit = 3; var tocEntryMinimum = 1; </script> <script src="/common/script/gsfx/kbtoc.js?13" type="text/javascript"></script>
概要
<script type="text/javascript">loadTOCNode(1, 'summary');</script>
本文讨论如何从 Access 数据库检索标识列值。
从 Jet 数据库检索标识值是不同于与 SQLServer, 因为 Jet 数据库不支持多语句批处理命令。 JetOLEDB 版本 4.0 提供支持 @@Identity SELECT 查询, 可以检索您连接上生成自动递增字段的值。 以运行查询, SELECT @@Identity 建议您使用其他 OleDbCommand 对象。 本文介绍如何使用二 OleDbCommand 来检索标识列值。
注意: 此功能适用于 OLEDB Microsoft Jet 4.0 数据库只。 早期版本的 Microsoft Jet OLEDB 不支持此功能。
更多信息
<script type="text/javascript">loadTOCNode(1, 'moreinformation');</script>
连接到 Access 数据库
<script type="text/javascript">loadTOCNode(2, 'moreinformation');</script> 要接到 Access 数据库并创建表与标识列, 请按照下列步骤操作:
1. | 启动 Microsoft Visual Studio NET 2002。 |
2. | 在 文件 菜单, 指向 新建 , 然后单击 项目 。 |
3. | 项目类型 下单击 VisualBasic 项目 。 模板 部分, 下单击 控制台应用程序 。 默认情况下, 创建 Module 1。 |
4. | 命名 MyJetApplication 项目, 然后单击 确定 。 |
5. | 用以下代码替换现有代码: Imports SystemImports System.DataImports System.Data.OleDbModule Module1 Sub Main() ' Open Connection Dim cnJetDB As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase") cnJetDB.Open() ' If the test table does not exist, create the Table. Dim strSQL As String strSQL = "CREATE TABLE AutoIncrementTest " & _ "(ID int identity, Description varchar(40), " & _ "CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID))" ' 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("Select * from AutoIncrementTest", cnJetDB) ' Command to Insert Records. Dim cmdInsert As New OleDbCommand() cmdInsert.CommandText = "INSERT INTO AutoIncrementTest (Description) VALUES (?)" cmdInsert.Connection = cnJetDB cmdInsert.Parameters.Add(New OleDbParameter("Description", OleDbType.VarChar, 40, "Description")) 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("Description") = "This is a Test Row 1" dtTest.Rows.Add(drTest) drTest = dtTest.NewRow drTest("Description") = "This is a Test Row 2" dtTest.Rows.Add(drTest) End SubEnd Module |
6. | 修改连接字符串指向 Access 数据库中数据源名称。 |
捕获标识列值
<script type="text/javascript">loadTOCNode(2, 'moreinformation');</script> 来汇总 RowUpdated 事件的 DataAdapter, 中步骤, 您来捕获标识列值为 Access 数据库中表列生成。 RowUpdated 事件, 中通过其他 Command 对象, 将执行 SELECT @ @ IDENTITY 查询, 然后您将分配到标识列由查询返回值。 最后, 调用 AcceptChanges 方法要接受列值的 DataRow 对象。
请标识列值, 陷阱执行以下步骤:
1. | 添加下列代码之前 Main 方法来创建另一个 OleDbCommand 对象用于 SELECT @ @ IDENTITY 查询: ' Create OleDbCommand for SELECT @@IDENTITY statement Private cmdGetIdentity As OleDbCommand |
2. | 以下代码附加到 Main 方法用于创建 OleDbCommand 类的新实例: ' Create another command to get IDENTITY value. cmdGetIdentity = New OleDbCommand() cmdGetIdentity.CommandText = "SELECT @@IDENTITY" cmdGetIdentity.Connection = cnJetDB |
3. | 以下代码附加到 Main 方法用于处理 RowUpdated 事件: ' Delegate for handling RowUpdated event. AddHandler oleDa.RowUpdated, AddressOf HandleRowUpdated |
4. | 以下代码附加到 Main 方法用于更新数据。 调用 Update 方法后引发 RowUpdated 事件。 ' Update the Data oleDa.Update(dtTest) |
5. | 以下代码附加到 Main 方法释放资源和除去 AutoIncrementTest 表: ' Drop the table cmdJetDB.CommandText = "DROP TABLE AutoIncrementTest" cmdJetDB.ExecuteNonQuery() ' Release the resources. cmdGetIdentity.Dispose() cmdGetIdentity = Nothing cmdInsert.Dispose() cmdInsert = Nothing cmdJetDB.Dispose() cmdJetDB = Nothing cnJetDB.Close() cnJetDB.Dispose() cnJetDB = Nothing |
6. | 以下 RowUpdated 事件处理代码添加到 Module 1: ' 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("ID") = Int32.Parse(cmdGetIdentity.ExecuteScalar().ToString()) Debug.WriteLine(e.Row("ID")) e.Row.AcceptChanges() End If End Sub |
7. | 在 调试 菜单, 单击 开始 以运行该应用程序。 标识列值输出窗口中显示。 |
完成代码列表
<script type="text/javascript">loadTOCNode(2, 'moreinformation');</script>
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("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase")
cnJetDB.Open()
' If the test table does not exist then create the Table
Dim strSQL As String
strSQL = "CREATE TABLE AutoIncrementTest " & _
"(ID int identity, Description varchar(40), " & _
"CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID))"
' 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("Select * from AutoIncrementTest", cnJetDB)
' Command to Insert Records
Dim cmdInsert As New OleDbCommand()
cmdInsert.CommandText = "INSERT INTO AutoIncrementTest (Description) VALUES (?)"
cmdInsert.Connection = cnJetDB
cmdInsert.Parameters.Add(New OleDbParameter("Description", OleDbType.VarChar, 40, "Description"))
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("Description") = "This is a Test Row 1"
dtTest.Rows.Add(drTest)
drTest = dtTest.NewRow
drTest("Description") = "This is a Test Row 2"
dtTest.Rows.Add(drTest)
' Create another Command to get IDENTITY Value
cmdGetIdentity = New OleDbCommand()
cmdGetIdentity.CommandText = "SELECT @@IDENTITY"
cmdGetIdentity.Connection = cnJetDB
' Delegate for Handling RowUpdated event
AddHandler oleDa.RowUpdated, AddressOf HandleRowUpdated
' Update the Data
oleDa.Update(dtTest)
' Drop the table
cmdJetDB.CommandText = "DROP TABLE AutoIncrementTest"
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("ID") = Int32.Parse(cmdGetIdentity.ExecuteScalar().ToString())
Debug.WriteLine(e.Row("ID"))
e.Row.AcceptChanges()
End If
End Sub
End Module
参考
<script type="text/javascript">loadTOCNode(1, 'references');</script>
232144 (http://support.microsoft.com/kb/232144/EN-US/)
有关详细信息, 请访问以下 MSDN 网站:
OleDbDataAdapter.RowUpdated 事件 http://msdn2.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.rowupdated(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.rowupdated(vs.71).aspx)