关闭可能尚未初始化的SqlDataReader

时间:2015-06-10 18:57:09

标签: c# exception-handling

我陷入了不同编译错误的循环中,我需要一些帮助。

所以情况1:在try块之外执行的SqlDataReader允许稍后关闭它,但是,将读者的例外保留为无法处理。

var cmd = String.Format("SQL COMMAND HERE");
var command = new SqlCommand(cmd, conSQL);
SqlDataReader readerSql = command.ExecuteReader();  //Unhandled Exceptions here
try
{
    while (readerSql.Read())
    {....}
}
catch (SqlException e)
{...}
finally
{
    readerSql.Close(); //Compiler error: Might not have been initialized          
}

案例2:读取器在try块内执行,读者异常可以处理,但读者不能在异常时关闭。

SqlDataReader readerSql;
try{
    readerSql = command.ExecuteReader();
    while (readerSql.Read())
    {...}
    readerSql.Close(); //Does not close on exceptions
}
catch (SqlException e)
{
    readerSql.Close(); //Compiler error: Might not have been initialized
}
finally
{
    if(readerSql != null)  //Compiler Error on if statement, same as below
        readerSql.Close(); //Compiler error: Might not have been initialized    
}

3 个答案:

答案 0 :(得分:3)

使用using声明,它解决了您的问题:

using语句确保即使在对象上调用方法时发生异常,也会调用Dispose。

答案 1 :(得分:1)

正如Alioza所说,最好的方法是使用声明。

using (var readerSql  = command.ExecuteReader()) {
    while (readerSql.Read()) {
        {....}
    }
}

https://msdn.microsoft.com/en-us/library/yh598w02.aspx(使用声明文档)

答案 2 :(得分:0)

您可以使用using语句,而不用担心结束。

using(SqlDataReader readerSql = command.ExecuteReader()){
     try{
            while (readerSql.Read())
            {....}
        }
        catch (SqlException e)
        {
           //execption
        }
}
相关问题