Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - Retrieving last inserted ID from MS Access database

I have the following set of code for a Sub program. It's inserting a row into a MSAccess Database using data provided in the containing form. What I would like to do is grab the ID number of this added record so that it can be set for a property of a window that is invoked when successfully added. I tried looking this up but I get something about @@IDENTITY but it's using an entirely different way of connecting.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming you have an auto increment column in the Tournaments table, you can do a "SELECT @@IDENTITY" to get the id of the last inserted record.

BTW, is the SanctioningIDTxt.Text unique? If so, can't you use that?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...