C# - 关闭SQL对象的最佳实践 [英] C# - closing Sql objects best practice

查看:120
本文介绍了C# - 关闭SQL对象的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有Sqlaccess一个C#的功能,它是强制关闭所有对象/句柄,或者一切都清理干净后自动退出功能

If you have a C# function with Sqlaccess, is it mandatory to close all objects/handles, or is everything cleaned up automatically once you exit the function

例如

void DoSqlStuff()
{
    SqlConnection sqlConn = new SqlConnection(...);
    SqlCommand cmd = new SqlCommand(...);
    SqlDataReader sqlData= null;

    sqlConn,Open();
    sqlData = cmd.ExecutReader();


    while(sqlData.Read())
    {
         ...
    }
}

它是可选的,建议或强制关闭SqlConn和SQLDATA?

Is it optional, recommended or mandatory to close SqlConn and SqlData?

谢谢

推荐答案

您应该尽快关闭SqlConnection对象你用它做。如果你没有那么连接将保持开放,并不会提供给处理其他请求。

You should close the SqlConnection object as soon as you're done with it. If you don't then the connection will remain open, and will not be available to handle other requests.

using语句是对这项有益的。这将在对象上调用Dispose()为您提供:

The using statement is useful for this. It will call Dispose() on the object for you:

using (SqlConnection cn = new SqlConnection(connectionString))
{   
    SqlCommand cm = new SqlCommand(commandString, cn)
    cn.Open();
    cm.ExecuteNonQuery();       
}

这篇关于C# - 关闭SQL对象的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆