ado.net crud操作出错

时间:2016-09-12 11:09:38

标签: c# asp.net-mvc ado.net

我想更新详细信息。我在数据访问类中有代码。但是在执行ExecuteScalar()之后,它会转到catch块并显示异常null

计划:

public bool UpdateData(Customer objcust) // passing model class object because it contains all customer properties.
{
    SqlConnection con = null;
   // string result = "";
    //int rows = 0;
    try
    {
        string connectionString = @"server=(local)\SQLExpress;database=CustDemo;integrated Security=SSPI;";
        con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("UPDATE Customer SET Name = @Name , Address = @Address, Gender =@Gender , City=@City WHERE Customer.CustomerID = @CustomerID",con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", objcust.Name);
        cmd.Parameters.AddWithValue("@Gender", objcust.Gender);
        cmd.Parameters.AddWithValue("@Address", objcust.Address);
        cmd.Parameters.AddWithValue("@City", objcust.City);

        con.Open();
        cmd.ExecuteScalar();

        return true;
    }
    catch(Exception ex)
    {
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

而不是cmd.ExecuteScalar();尝试使用

cmd.ExecuteNonQuery (); 

ExecuteNonQuery用于专门执行UPDATE,INSERT或DELETE语句。