C# · 12月 27, 2021

C#使用自动增量获取插入ID

我正在使用此方法在表中插入一行: 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();

我还有id列有自动增量.
而且我想知道是否可以获取插入新行时创建的id.

解决方法 您可以访问MysqLCommand LastInsertedId属性. cmd.ExecuteNonQuery();long id = cmd.LastInsertedId;