Home > Back-end >  How to check which primary key a record was assigned to in C#?
How to check which primary key a record was assigned to in C#?

Time:11-01

I'm using the OleDBConnectivity system to connect and use a Microsoft Access database.

I'm adding a record to the table in the database called "PayInfo", and the primary key is automatically set to the next available integer. How do I check what the value of the primary key it was assigned to is? I know this is probably an awful idea, but the only thing I could think of was to re-read the database using the entered values. The issue with this, though it's very unlikely, is that its possible to have 2 identical records stored in the database, their only difference being the primary key, and I need to be able to read the specific one.

My current subroutine for adding the record to the database is as follows:

OleDbCommand command = connection.CreateCommand();
connection.Open();

// The SQL statement:
command.CommandText = "INSERT INTO PayInfo ([UserID], [FullName], [CardType], [CardNo], [CVV], [ExpDate], [Address])"  
                      "VALUES ('"   Global.UserID.ToString()   "','"   PayInfo[6]   "','"   PayInfo[0]   "','"   PayInfo[1]   "','"   PayInfo[2]   "','"   exp   "','"   adress   "')";

command.Connection = connection;

command.ExecuteNonQuery(); //executes the SQL command.

connection.Close();
return true;  //Successful transaction

CodePudding user response:

After executing your insert query, you need to execute another query to get the generated primary key:

command.Parameters.Clear();
command.CommandText = "SELECT @@IDENTITY";
int primaryKey = Convert.ToInt32(Command.ExecuteScalar());

See Microsoft: Retrieving Identity or Autonumber Values for more details:

The Jet database engine does not support the execution of multiple statements in a batch or the use of output parameters, so it is not possible to use either of these techniques to return the new Autonumber value assigned to an inserted row. However, you can add code to the RowUpdated event handler that executes a separate SELECT @@IDENTITY statement to retrieve the new Autonumber value.

  • Related