Getting the ID of Inserted Row in C#
When inserting a new row into a database table, it's often necessary to obtain the ID of the newly created record. However, the code provided in the question failed to retrieve the ID correctly.
The issue lies in the usage of ExecuteScalar(). This method retrieves only the first column of the first row of the result set, which in this case is an integer value of 0 since the query doesn't return any rows.
To correctly obtain the ID of the inserted row, follow these steps:
Here's the revised code:
This updated code first executes the insert command and then retrieves the ID of the newly inserted row from the LastInsertedId property of the command object. This properly retrieves the correct ID value for further processing.
The above is the detailed content of How to Retrieve the ID of an Inserted Row in C#?. For more information, please follow other related articles on the PHP Chinese website!