当我的select命令没有任何结果时,它会抛出异常。相反,我想毫无例外地继续这个过程。如何通过检查是否有从select语句中检索到的数据来控制它?
这是我的问题:
sqlid = new SqlCommand("SELECT TOP 1 Proj_id FROM Proj_details WHERE Front_end = '" + strfrontend + "'ORDER BY Date_time desc", con);
id = sqlid.ExecuteScalar().ToString();
答案 0 :(得分:4)
使用例外控制程序流程(如其他答案所示)是wrong solution。如果可以接受不返回结果,请在调用ExecuteScalar()
之前检查ToString()
返回的值。
按definition,如果没有结果,ExecuteScalar将返回null。
object val = sqlid.ExecuteScalar();
if( val != null ){
id = val.ToString();
}else{
// do something (or nothing) and continue
}
答案 1 :(得分:0)
尝试使用ExecuteReader而不是ExecuteScalar并以这种方式处理空结果:
SqlCommand sqlid = new SqlCommand("SELECT TOP 1 Proj_id FROM Proj_details WHERE Front_end = '" + strfrontend + "'ORDER BY Date_time desc", con);
SqlDataReader dr = sqlid.ExecuteReader();
if (dr.Read())
{
id = dr[0].ToString();
}
else
{
// handle empty result here
}
答案 2 :(得分:0)
这样就够了吗?
SqlDataReader rd = cmdLoad4.ExecuteReader();
if (rd.HasRows)
{
// input what you want.
}
else
{
//input the exception
}
答案 3 :(得分:-1)
try-catch块不起作用吗?
try
{
//Execute your SQL-statement here
}
catch(SqlException)
{
//If you want something specific to happen when the
//exception is thrown, put that here.
}
http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx
答案 4 :(得分:-1)
使用try / catch语句封装它:
try
{
sqlid = new SqlCommand("SELECT TOP 1 Proj_id FROM Proj_details
WHERE Front_end = '" + strfrontend
+ "'ORDER BY Date_time desc", con
);
id = sqlid.ExecuteScalar().ToString();
}
catch(exception)
{
// do something with the exception
}