c# - 检索刚刚添加的行的唯一 ID

标签 c# asp.net sql database dataset

我是 asp.net 的新手。我正在通过 SQL 命令执行一个简单的插入查询。现在我想检索这个新插入的行的唯一 ID 并将其存储在一个数组中。我不知道如何解决这个问题。

我的代码

foreach (GridViewRow gvrow in gvuserdata.Rows)
        {

            string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
            " values(@carid, @username, @carname,@price,@startdate,@enddate)";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.AddWithValue("@carid", gvrow.Cells[0].Text);
            cmd.Parameters.AddWithValue("@username", gvrow.Cells[1].Text);
            cmd.Parameters.AddWithValue("@carname", gvrow.Cells[2].Text);
            cmd.Parameters.AddWithValue("@price", gvrow.Cells[3].Text);
            cmd.Parameters.AddWithValue("@startdate", gvrow.Cells[4].Text);
            cmd.Parameters.AddWithValue("@enddate", gvrow.Cells[5].Text);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
         //I want to store ID for this row after insert command   
        }

最佳答案

将 Select Scope_Identity() 与 Execute Scalar 结合使用:

int returnID = 0;
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName,  
   CarName,Price,startdate,enddate)" + " values(@carid, @username, 
   @carname,@price,@startdate,@enddate); Select Scope_Identity()";
...
returnID = (int)cmd.ExecuteScalar();

关于c# - 检索刚刚添加的行的唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15893439/

相关文章:

c# - .NET Selenium NoSuchElementException; WebDriverWait.Until() 不起作用

JavaScript window.location 不起作用

c# - 缓存数据列表 asp.net c#

asp.net - 当主要内容没有填满页面时,如何让母版页上的 ‘footer’ 内容向下推

c# - 如何使 Windows 窗体上的 dataGridView 中的最后一行始终显示,同时仍允许剩余行滚动

c# - 如何在T4模板中 "read"EF6 EntityTypeConfiguration?

c# - 自定义列表到数组数组

mysql - 我应该在 MySQL 中创建一个条目可以是多个字符串的列吗?

java - 根据每天创建的时间戳更新和插入大量 SQL 行的最佳方法是什么?

mysql - DISTINCT 不删除重复项