I am doing a project where i have to count a column's values in SQL Server, and return it's sum.
I use this query.
select sum(Charges)
from Kitchen
where Customer_ID = '1'
and Date Between 'Friday,January 19,2018' AND 'Sunday,January 21,2018';
It is working fine in SQL Server Management Studio. But when I am using this in C# code it is throwing an exception of null value.
Exception is.
Data is Null. This method or property cannot be called on Null values.
Here is the code for better understanding:
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();
Note: column datatype is int
.
Please guide me how to solve this issue.
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();
ADO.NET is very easy to get wrong, and that SQL is hugely dangerous. I strongly recommend tools like Dapper to help here:
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;
This solves parameterization, command building, and output processing all in one go. It'll even open and close the connection!
Additional note: be very careful with DateTime.Now
and databases - it might be tricky around DST changes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.