-5

当我的选择命令没有任何结果时,它会引发异常。相反,我想毫无例外地继续这个过程。如何通过检查是否有从 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();
4

5 回答 5

4

使用异常来控制程序流程(如其他答案所建议的)是错误的解决方案。如果可以接受不返回任何结果,请ExecuteScalar()在调用ToString()它之前检查返回的值。

根据定义,如果没有结果,ExecuteScalar 将返回 null。

object val = sqlid.ExecuteScalar();
if( val != null ){
    id = val.ToString();
}else{
    // do something (or nothing) and continue
}

另请参阅:ExecuteScalar 抛出 NullReferenceException

于 2012-08-08T06:44:15.240 回答
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
}
于 2012-08-08T06:45:18.840 回答
0

这足够了吗?

 SqlDataReader rd = cmdLoad4.ExecuteReader();
 if (rd.HasRows)
{
// input what you want.
}
else
{
//input the exception
}
于 2017-07-24T07:24:46.530 回答
-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

于 2012-08-08T06:41:30.990 回答
-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
}
于 2012-08-08T06:43:00.653 回答