[英]C# Get insert id with Auto Increment
I am using this method to insert a row into a table: 我正在使用此方法在表中插入一行:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = @"INSERT INTO Wanted (clientid,userid,startdate,enddate) VALUES" +
"(@clientid, @userid, @startdate, @enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("@clientid", userId);
cmd.Parameters.AddWithValue("@userid", "");
cmd.Parameters.AddWithValue("@startdate", start);
cmd.Parameters.AddWithValue("@enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
I hav also id column that have Auto Increment
. 我也有id具有Auto Increment
列。 And i want to know if it possible to get the id that is created when i insert a new row. 我想知道是否有可能获得插入新行时创建的ID。
You can access the MySqlCommand LastInsertedId property. 您可以访问MySqlCommand LastInsertedId属性。
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = @"INSERT INTO Wanted (clientid,userid,startdate,enddate) "
+ "VALUES(@clientid, @userid, @startdate, @enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("@clientid", userId);
**cmd.Parameters["@clientid"].Direction = ParameterDirection.Output;**
cmd.Parameters.AddWithValue("@userid", "");
cmd.Parameters.AddWithValue("@startdate", start);
cmd.Parameters.AddWithValue("@enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Basically you should add this to end of your CommandText: 基本上你应该将它添加到CommandText的末尾:
SET @newPK = LAST_INSERT_ID();
and add another ADO.NET parameter "newPK". 并添加另一个ADO.NET参数“newPK”。 After command is executed it will contain new ID. 执行命令后,它将包含新ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.