Search code examples
sqlvb.netrefresholedb

How to refresh database between Inserting and Selecting


I am trying to get data from a record in a database that has just been creating, but no data is found from it.

I've tried using different connections in the hope that it would be able to 'see' the new data, but this doesn't work and I am stuck!

Using oCmd As New OleDbCommand("Insert Into Users (FirstName, LastName, Username, `Password`, Teacher) Values (@firstName, @lastName, @username, @password, 0)", myConnection)
   oCmd.Parameters.Add("@firstName", OleDbType.VarChar, 255).Value = txtFirstName.Text
   oCmd.Parameters.Add("@lastNamee", OleDbType.VarChar, 255).Value = txtLastName.Text
   oCmd.Parameters.Add("@username", OleDbType.VarChar, 255).Value = txtUsername.Text
   oCmd.Parameters.Add("@password", OleDbType.VarChar, 255).Value = txtPassword.Text
   oCmd.ExecuteNonQuery()
End Using
Dim userID As String = ""
Using ocmd As New OleDbCommand("Select * From Users Where FirstName = @firstName And LastName = @lastName", myConnection)
   ocmd.Parameters.Add("@firstName", OleDbType.Char, 255).Value = txtFirstName.Text
   ocmd.Parameters.Add("@lastName", OleDbType.Char, 255).Value = txtLastName.Text
   Dim dataReader As OleDbDataReader = ocmd.ExecuteReader()
   While dataReader.Read
      userID = dr("UserID")
   End While

The error that is shown is

System.InvalidOperationException: 'No data exists for the row/column.'

All I want is to get the userID of the record that has been created. Any help is appreciated.


Solution

  • To get the last entered ID.

    Dim cmd1 As New OleDbCommand("Select @@IDENTITY", myConnection)
    Dim itgID As Integer = CInt(cmd1.ExecuteScalar)