Home > Database > Mysql Tutorial > How to Retrieve the Last Inserted Row ID in C#?

How to Retrieve the Last Inserted Row ID in C#?

Barbara Streisand
Release: 2024-11-08 02:20:02
Original
287 people have browsed it

How to Retrieve the Last Inserted Row ID in C#?

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:

  1. 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);
    Copy after login
  2. 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();
    Copy after login
  3. 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;
    Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template