2012-02-23 58 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