我是 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/