C#如何获取自增插入的id?

16

我正在使用这种方法向表中插入一行:

            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。


这是你想要的吗?http://stackoverflow.com/questions/7982520/get-autoincrement-value-after-insert-query-in-mysql - JeremyWeir
不,我想要我插入的ID。 - YosiFZ
3个回答

34

您可以访问 MySqlCommand 的 LastInsertedId 属性。

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

谢谢,它可以工作!如果我想在一个插入语句中插入多行,是否有可能获取每个ID? - YosiFZ
谢谢!我读过C#没有这样的属性,所以我正在为此编写一个方法! - Jack

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

0

基本上,您应该将此添加到CommandText的末尾:

SET @newPK = LAST_INSERT_ID();

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接