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:
<code class="csharp">MySqlConnection conn = new MySqlConnection(Global.ConnectionString); conn.Open();</code>
<code class="csharp">MySqlCommand dbcmd = conn.CreateCommand(); dbcmd.CommandText = "INSERT INTO test SET var = @var";</code>
<code class="csharp">long insertID = dbcmd.LastInsertedId;</code>
Using this method, you can accurately retrieve the last insert ID generated by your MySql queries.
The above is the detailed content of How to Retrieve the Last Insert ID in MySQL Using Connector .NET?. For more information, please follow other related articles on the PHP Chinese website!