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:
MySqlConnection conn = new MySqlConnection(Global.ConnectionString);
conn.Open();
MySqlCommand dbcmd = conn.CreateCommand();
dbcmd.CommandText = "INSERT INTO test SET var = @var";
long insertID = dbcmd.LastInsertedId;
Using this method, you can accurately retrieve the last insert ID generated by your MySql queries.
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