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

How to Retrieve the ID of an Inserted Row in C#?

Susan Sarandon
Release: 2024-11-12 07:07:02
Original
1077 people have browsed it

How to Retrieve the ID of an Inserted Row in C#?

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:

  1. Execute the insert statement using ExecuteNonQuery().
  2. Retrieve the ID of the inserted item using LastInsertedId.

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!

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