3 回答
TA贡献1785条经验 获得超8个赞
您有3 个案例需要实施:
根本没有数据:检查
null
无效数据,例如
1 + 2 + NULL + 3 == NULL
:检查DBNull.Value
有效数据,例如
1 + 2 + 3 == 6
:借助Convert.ToDecimal()
代码:
// wrap IDisposable into using
using (SqlConnection con = new SqlConnection("***COnString**")) {
con.Open();
//DONE: Make sql readable
//DONE: Make sql parametrized
//TODO: you may want to change eb_number = eb_number into INNER JOIN
string sql =
@"SELECT SUM (Total_Hours_Day)
FROM Sign_In_Out_Table,
User_Table
WHERE User_Table.FirstName = @prm_FirstName
AND Sign_In_Out_Table.eb_number = User_Table.eb_number
AND Date BETWEEN GETDATE() - 14 AND GETDATE()";
using (SqlCommand comm = new SqlCommand(sql, con)) {
//TODO: Better specify RDBMS type explictly with "comm.Parameters.Add(...)"
comm.Parameters.AddWithValue(
"@prm_FirstName", Search_Username_Alerts_Admin_txtbox.Text);
var result = comm.ExecuteScalar();
if (null == result) { // No Data
MessageBox.Show("No Data Exist");
}
else if (DBNull.Value == result) { // We have the Data and it's RDBMS Null
MessageBox.Show("Data Exist, but not valid.");
}
else { // We have a valid Decimal
Decimal sum = Convert.ToDecimal(result);
//TODO: put the relevant code here
}
}
}
TA贡献2041条经验 获得超4个赞
我会使用 decimal.tryparse 来查看是否返回了数据
SqlConnection con = new SqlConnection("***COnString**");
con.Open();
SqlCommand comm = new SqlCommand("SELECT SUM (Total_Hours_Day) FROM Sign_In_Out_Table, User_Table WHERE User_Table.FirstName = '" + Search_Username_Alerts_Admin_txtbox.Text + "' AND Sign_In_Out_Table.eb_number = User_Table.eb_number AND Date between GETDATE()-14 and GETDATE()", con);
string TotalHoursFortnight = (comm.ExecuteScalar()).ToString();
con.Close();
decimal sum = 0;
decimal temp;
if(!decimal.TryParse(TotalHoursFortnight, out temp))
{
MessageBox.Show("No Data Exists");
}
else
{
sum += temp;
MessageBox.Show(Search_Username_Alerts_Admin_txtbox.Text + ":" + Environment.NewLine + " Hours Worked = " + TotalHoursFortnight, ("Working Info Admin"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
TA贡献1784条经验 获得超2个赞
您需要为查询结果检查 null
var result = comm.ExecuteScalar();
if(result != null){
decimal TotalHoursFortnight = Convert.ToDecimal(comm.ExecuteScalar());
// move remain code to if block
}
并且if (Search_Username_Alerts_Admin_txtbox.Text == DBNull)应该改为
if (Convert.IsDBNull(Search_Username_Alerts_Admin_txtbox.Text){
}
- 3 回答
- 0 关注
- 99 浏览
添加回答
举报