在ado.net crud操作中出错

本文关键字:出错 操作 crud ado net | 更新日期: 2023-09-27 18:06:49

我想更新细节。我有一个数据访问类的代码。但是在执行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;
    }
}

在ado.net crud操作中出错

代替cmd.ExecuteScalar();尝试使用

cmd.ExecuteNonQuery (); 

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