我正在使用此方法在表中插入一行:
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();
我还拥有Auto Increment
的id列。
我想知道是否有可能获得插入新行时创建的id。
答案 0 :(得分:25)
您可以访问MySqlCommand LastInsertedId属性。
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
答案 1 :(得分:1)
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();
答案 2 :(得分:0)
基本上你应该将它添加到CommandText的末尾:
SET @newPK = LAST_INSERT_ID();
并添加另一个ADO.NET参数“newPK”。执行命令后,它将包含新ID。