"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve the Last Insert ID in MySQL Using Connector .NET?

How to Retrieve the Last Insert ID in MySQL Using Connector .NET?

Published on 2024-11-08
Browse:308

How to Retrieve the Last Insert ID in MySQL Using Connector .NET?

Retrieving Last Insert ID in MySql Using Connector .NET

In MySql, the last insert ID refers to the identifier assigned to the newly inserted row. This value can be valuable in certain scenarios, such as populating foreign key relationships.

Originally, the ExecuteNonQuery method of the MySqlHelper class was assumed to return the last insert ID. However, this assumption is incorrect; it merely indicates the number of rows affected by the query. To retrieve the actual last insert ID:

  1. Establish a MySql Connection:
    Create a MySql connection and open it explicitly.
MySqlConnection conn = new MySqlConnection(Global.ConnectionString);
conn.Open();
  1. Execute the Query:
    Create a MySql command and execute the insert query using it.
MySqlCommand dbcmd = conn.CreateCommand();
dbcmd.CommandText = "INSERT INTO test SET var = @var";
  1. Retrieve the Last Insert ID:
    After executing the query, access the LastInsertedId property of the command object to obtain the last insert ID.
long insertID = dbcmd.LastInsertedId;

Using this method, you can accurately retrieve the last insert ID generated by your MySql queries.

Release Statement This article is reprinted at: 1729725847 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3