how to close a sqlconnection in asp.net

﹥>﹥吖頭↗ 提交于 2019-12-11 07:28:23

问题


i would like to know if there's something wrong in this asp.net code:

mydatareader = mycmd.executeReader()
if myDataReader.HasRow then
      // Do something
end if
myConnection.Close()

If i avoid to call a "MyDataReader.Close()" does the connection close anyway ? I ask this because i'm assuming that if call a "MyConn.Close" it automatically close the associated datareader... or am i wrong ?

Thanks


回答1:


You have to close your reader instead of closing the connection. Have a look here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx




回答2:


The best practice to perform such operations is as follows:

using(SqlConnection connection = new SqlConnection(connStr)) {
    connection.Open();

    SqlCommand command = new SqlCommand(connection, "SELECT...");
    SqlDataReader reader = command.ExecuteReader();
    // Fill your container objects with data
}

The using statement:

Defines a scope, outside of which an object or objects will be disposed.

So you can be assured that your connection, command and reader variables will be closed and disposed accordingly when exiting the using block.




回答3:


If you neither close the data reader nor the connection, garbage collector will do it for you. On the other side, this will probably affect the performance of your application.




回答4:


I'm not absolutely sure but I'm always using try-catch-finally block for db actions:

using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
    using (SqlCommand cmmnd = new SqlCommand("SELECT Date();", cnn))
    {
        try
        {
            cnn.Open();
            using (SqlDataReader rdr = cmmnd.ExecuteReader())
            {
                if (rdr.Read()) { result = rdr[0].ToString(); }
            }
        }
        catch (Exception ex) { LogException(ex); }
        finally { cnn.Close(); }
    }
}


来源:https://stackoverflow.com/questions/2850382/how-to-close-a-sqlconnection-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!