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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15373851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:32:28  来源:igfitidea点击:

C# Get insert id with Auto Increment

c#mysql.netsql

提问by MTA

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. And i want to know if it possible to get the id that is created when i insert a new row.

我也有 id 列Auto Increment。我想知道是否有可能获得插入新行时创建的 id。

采纳答案by dugas

You can access the MySqlCommand LastInsertedId property.

您可以访问 MySqlCommand LastInsertedId 属性。

cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;

回答by pero

Basically you should add this to end of your CommandText:

基本上你应该把它添加到你的 CommandText 的末尾:

SET @newPK = LAST_INSERT_ID();

and add another ADO.NET parameter "newPK". After command is executed it will contain new ID.

并添加另一个 ADO.NET 参数“newPK”。命令执行后,它将包含新的 ID。

回答by Tim

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();