从MS Access数据库中检索最后插入的ID

时间:2012-02-23 17:20:44

标签: vb.net visual-studio-2010 ms-access

我有一组Sub程序的代码。它使用包含表单中提供的数据将一行插入MSAccess数据库。我想要做的是获取此添加记录的ID号,以便可以为成功添加时调用的窗口属性设置它。我尝试了这个,但我得到了关于@@IDENTITY的一些内容,但是它采用了完全不同的连接方式。

Private Sub CreateTournament_Click(sender As System.Object, e As System.EventArgs) Handles CreateTournament.Click
    ' TODO: Check the form for errors, or blank values.
    ' Create the tournament in the database, add the values where needed. Close the form when done.

    Dim cn As OleDbConnection
    Dim cmd As OleDbCommand
    Dim dr As OleDbDataReader
    Dim icount As Integer
    Dim str As String

    Try
        cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Master.mdb'")
        cn.Open()
        str = "insert into Tournaments (SanctioningID,TournamentName,TournamentVenue,TournamentDateTime,TournamentFirstTable,Game,Format,OrganizerID) values(" _
            & CInt(SanctioningIDTxt.Text) & ",'" & Trim(TournamentNameTxt.Text) & "','" & _
            "1" & "','" & EventDateTimePck.Value & "','" & TableFirstNumberNo.Value & "','" & GameList.SelectedIndex & "','" & FormatList.SelectedIndex & "','" & Convert.ToInt32(ToIDTxt.Text) & "')"

        'string stores the command and CInt is used to convert number to string
        cmd = New OleDbCommand(Str, cn)
        icount = cmd.ExecuteNonQuery
        MessageBox.Show(icount)
        'displays number of records inserted
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try

    Me.Close()

    Dim n As New TournamentWindow ' Open a new Tournament window if everything is successful
    n.TournID = Counter '<< This should be set to the ID of the most recently inserted row
    n.Show(HomeForm)'Invoke the form and assign "HomeForm" as it's parent.

End Sub

1 个答案:

答案 0 :(得分:1)

假设您在Tournaments表中有一个自动增量列,您可以执行“SELECT @@ IDENTITY”来获取最后插入记录的ID。

BTW,SanctioningIDTxt.Text是唯一的吗?如果是这样,你不能使用它吗?