
07-23-2012, 11:57 AM
|
 |
Centurion
|
|
Join Date: Feb 2005
Posts: 113
|
|
Get ID from new record
|
Hello, I need to get the ID (Primary Key) from the record that I just added to my database. I've been looking for answers on MSDN and other places on the internet for a couple of days but I cant get any of the sample code to work with mine because there are so many different ways of doing things and I'm pretty new to writing database code. Here is my code so far.
Code:
Dim da As OleDbDataAdapter
Dim qry As String = _
"SELECT ID, Species, Information " & _
"FROM tblSpecies"
da = New OleDbDataAdapter(qry, G_Connection1)
dsQuery = New DataSet()
da.Fill(dsQuery)
da.InsertCommand = New OleDbCommand( _
"INSERT INTO tblSpecies(Species, Information) " & _
"VALUES(@Species, @Information) " & _
"SELECT ID = @@IDENTITY")
da.InsertCommand.Connection = G_Connection1
da.InsertCommand.Parameters.Add("@Species", OleDbType.VarChar, 255, "Species")
da.InsertCommand.Parameters.Add("@Information", OleDbType.Variant, txtInfo.MaxLength, "Information")
Dim dr As DataRow
'get a refference to a new row
dr = dsQuery.Tables(0).NewRow
If txtSpecies.Text = "" Then
dr("Species") = "Unknown"
Else
dr("Species") = txtSpecies.Text
End If
dr("Information") = txtInfo.Text
dsQuery.Tables(0).Rows.Add(dr)
da.Update(dsQuery)
dsQuery.AcceptChanges()
da.Dispose()
dsQuery.Clear()
Me.Close()
|
|