Retrieving Inserted Row ID in C#
Obtaining the ID of a row inserted using an AUTO_INCREMENT field is essential for subsequent processing. However, in certain scenarios, executing an insert query may not yield the expected ID value.
To resolve this issue, consider the following approach:
Modify the Insert Statement:
Instead of specifying the column values directly in the query, you can use parameter placeholders and set the parameter values separately. This ensures a proper assignment of values:
MySqlCommand comm = connect.CreateCommand(); comm.CommandText = insertStatement; comm.Parameters.AddWithValue("@invoiceDate", invoiceDate); comm.Parameters.AddWithValue("@bookFee", bookFee); comm.Parameters.AddWithValue("@adminFee", adminFee); comm.Parameters.AddWithValue("@totalFee", totalFee); comm.Parameters.AddWithValue("@customerId", customerId);
Execute the Insert Query:
Execute the insert command using ExecuteNonQuery(). This method returns the number of rows affected by the query:
int rowsAffected = comm.ExecuteNonQuery();
Retrieve the Last Inserted ID:
After successfully executing the insert query, you can retrieve the ID of the inserted row using LastInsertedId:
long id = comm.LastInsertedId;
The above is the detailed content of How to Retrieve the Last Inserted Row ID in C#?. For more information, please follow other related articles on the PHP Chinese website!