简体   繁体   中英

Closing An SqlDataReader that might not have been initialized

I'm stuck in a cycle of different compiler errors and I need some assistance.

So case 1: SqlDataReader executed outside of try block allows closing it later, however, leaves the reader exceptions unhanded.

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          
}

Case 2: Reader is executed inside try block, reader exceptions can be handled, however, reader cannot be closed on exceptions.

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    
}

Use the using statement, it solves your issue:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

As Alioza says the best method is the using statement.

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

https://msdn.microsoft.com/en-us/library/yh598w02.aspx (using statement documentation)

you can use the using statement and not worry about closing.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM