2012-02-23 59 views
1

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

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

假设你已经在赛事表的自动递增列,你可以做一个“SELECT @@ IDENTITY”来获得最后插入记录的ID。

顺便说一句,是SanctioningIDTxt.Text的独特之处吗?如果是这样,你不能使用它?

+0

不是。如果某人没有制裁号码,则默认为-1。所以可以有多个-1值。关于@@ IDENTITY的问题,不是说它会发生,但如果别人也添加了一条记录,它会给出最后一个还是我插入的那个? – 2012-02-23 17:32:47

+0

它会给你最后一个。 – 2012-02-23 17:40:34

+0

猜猜我必须确保数据库已被锁定,并且只能被程序的一个实例使用。谢谢。 – 2012-02-23 17:48:26