如何知道行是否更新

时间:2016-07-07 11:12:52

标签: c# sql

我需要阻止用户在应用程序上写入别人的批准。我已经放入了IS NULL,它可以阻止它覆盖数据,但我需要显示一个标签,表示记录未经更新已经批准。

我如何知道sql查询是否更新或没有获取该信息以便我可以执行If语句。

If row updated then 
    label.text = "data approved" 
else   
    label.text = "You can not approve this as it's already approved"


CheckBox ckb = (CheckBox)sender;
        GridViewRow row = (GridViewRow)ckb.Parent.Parent;           //Get row selected
        int idx = row.RowIndex;

        //Get activity number ID for update query
        Label lblDHActivityNoApp = (Label)row.Cells[0].FindControl("lblDHActivityNoApp");
        string Number = lblDHActivityNoApp.Text.ToString();

        string connectionString = ConfigurationManager.ConnectionStrings["PlusConnectionString"].ConnectionString;
        string UpdateSql = "UPDATE Activities SET Status = @Status, ApprovedBy=@ApprovedBy, ApprovedDate=@ApprovedDate WHERE ApprovedBy IS NULL and (ActivityNo=@No)";
        //Create SQL connection
        SqlConnection con = new SqlConnection(connectionString);

        //Create SQL Command And Sql Parameters
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = UpdateSql;

        SqlParameter Status = new SqlParameter("@Status", SqlDbType.VarChar, 40);
        Status.Value = "Approved";
        cmd.Parameters.Add(Status);

        SqlParameter ApprovedDate = new SqlParameter("@ApprovedDate", SqlDbType.VarChar, 50);
        DateTime myDateTime = DateTime.Now; ;
        ApprovedDate.Value = myDateTime.ToString("dd/MM/yy HH:mm:ss");
        cmd.Parameters.Add(ApprovedDate);

        SqlParameter ApprovedBy = new SqlParameter("@ApprovedBy", SqlDbType.VarChar, 40);
        ApprovedBy.Value = (string)Session["Username"];
        cmd.Parameters.Add(ApprovedBy);

        SqlParameter No = new SqlParameter("@No", SqlDbType.VarChar, 50);
        No.Value = Number;
        cmd.Parameters.Add(No);

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            gbDHdetailsApp.DataBind();  //Reloads gridview with checked data       
        }

        catch (SqlException ex)
        {
            string errorMessage = "Not approved, please contact support";
            errorMessage += ex.Message;
            throw new Exception(errorMessage);
        }

        finally
        {
            con.Close();
        }

2 个答案:

答案 0 :(得分:4)

ExecuteNonQuery返回受影响的行数。如果为0,则可以抛出Exception

答案 1 :(得分:1)

ExecuteNonQuery()返回受影响的行数,返回类型为INT,因此您可以这样做

int rowsAffected = cmd.ExecuteNonQuery();

if(rowsAffected > 0)
{
  // do something
}