空值,例外

时间:2018-01-21 19:30:01

标签: c# sql null

我正在做一个项目,我必须在SQL Server中计算列的值,并返回它的总和。

我使用此查询。

select sum(Charges) 
from Kitchen 
where Customer_ID = '1' 
  and Date Between 'Friday,January 19,2018' AND 'Sunday,January 21,2018'; 

它在SQL Server Management Studio中运行良好。但是当我在C#代码中使用它时,它会抛出一个null值的异常。

例外是。

  

数据是空的。无法在Null值上调用此方法或属性。

以下是更好理解的代码:

con.Open();

string selectSQLC = "select sum(Charges) from Kitchen where Customer_ID='"+txtCustomerID.Text  +"' and Date Between '"+dateofarrival +"' and '"+DateTime.Now+"'";

SqlCommand cmdCC = new SqlCommand(selectSQLC, con);

SqlDataReader rdCC;

rdCC = cmdCC.ExecuteReader();

while (rdCC.Read())
{
    KitchenBill = rdCC.GetInt32(0);
}

TotalAmount = KitchenBill + TotalAmount;   

con.Close();

Here is the SS of SSMS

注意:列数据类型为int

请指导我如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

 con.Open();

string selectSQLC = "select sum(Charges) from Kitchen where Customer_ID=@Customer_ID and Date Between @date1  and @date2";

SqlCommand cmdCC = new SqlCommand(selectSQLC, con);
SqlParameter param  = new SqlParameter();
        param.ParameterName = "@Customer_ID";
        param.Value         = txtCustomerID.Text;
SqlParameter paramd1  = new SqlParameter();
        paramd1.ParameterName = "@date1";
        paramd1.Value         = dateofarrival;
SqlParameter paramd2  = new SqlParameter();
        paramd2.ParameterName = "@date2";
        paramd2.Value         = DateTime.Now;
cmdCC.Parameters.Add(param);
cmdCC.Parameters.Add(paramd1);
cmdCC.Parameters.Add(paramd2);
 SqlDataReader rdCC;

rdCC = cmdCC.ExecuteReader();

while (rdCC.Read())
{
    KitchenBill = rdCC.GetInt32(0);
}

TotalAmount = KitchenBill + TotalAmount;   

con.Close();

答案 1 :(得分:2)

ADO.NET很容易出错,而且SQL非常危险。我强烈推荐像Dapper这样的工具来帮助:

var KitchenBill = con.QuerySingle<int>(@"
    select sum(Charges) from Kitchen
    where Customer_ID=@customerID
    and Date Between @start and @end",
    new {
        customerId = txtCustomerID.Text,
        start = dateofarrival,
        end = DateTime.Now
    });

TotalAmount = KitchenBill + TotalAmount; 

这一次解决了参数化,命令构建和输出处理。它甚至可以打开和关闭连接!

附加说明:对DateTime.Now和数据库非常小心 - 在DST更改时可能会很棘手。