gpt4 book ai didi

c# - 如何获取 LAST_INSERT_ID();

转载 作者:行者123 更新时间:2023-12-01 00:03:22 26 4
gpt4 key购买 nike

我环顾四周,仍然对如何获取最后插入的 ID 感到困惑。我在正在执行的 mysql 语句末尾添加了语句 SELECT LAST_INSERT_ID();。我将值存储在 prID = Convert.ToInt32(cmd.ExecuteScalar()); 此命令在我的数据库中创建两个实例。我很确定我需要将这两个语句分开,但不确定如何在仍然获得最后一个 ID 的同时。

          try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "INSERT INTO pull_requests (repoID, branchID, fileID, prStatus, prComments) VALUES (@rID, @bID, @fID, @prS, @prC); SELECT LAST_INSERT_ID();";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@rID", RI);
cmd.Parameters.AddWithValue("@bID", BI);
cmd.Parameters.AddWithValue("@fID", FI);
cmd.Parameters.AddWithValue("@prS", 0);
cmd.Parameters.AddWithValue("@prC", comment);
prID = Convert.ToInt32(cmd.ExecuteScalar());

cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();

最佳答案

您只需调用cmd.ExecuteNonQuery() 即可执行插入语句。返回时,cmd 对象将填充其 .LastInsertedId 属性。

像这样:

try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "INSERT INTO pull_requests (repoID, branchID, fileID, prStatus, prComments) VALUES (@rID, @bID, @fID, @prS, @prC);";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@rID", RI);
cmd.Parameters.AddWithValue("@bID", BI);
cmd.Parameters.AddWithValue("@fID", FI);
cmd.Parameters.AddWithValue("@prS", 0);
cmd.Parameters.AddWithValue("@prC", comment);
cmd.ExecuteNonQuery();

long lastId = cmd.LastInsertedId;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();

关于c# - 如何获取 LAST_INSERT_ID();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53639746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com