为什么总是紧密数据库连接? [英] Why always close Database connection?

查看:106
本文介绍了为什么总是紧密数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

连接到数据库消耗大量资源的权利(或没有)的?结果
那么,为什么总是关闭应用程序中的数据库连接,如果你要再次打开它?

Connecting to database consumes a lot of resources right (or not)?
So, why always close a database connection in your application if you have to open it again?

我可以只是让我的整个应用程序全局可用此连接,这样其他类和方法可以重复使用吗?

Can I just make this connection available globally throughout my application so that other classes and methods can reuse it?

例如:(伪code)

public class PopulateGridViews()
{
    public SqlConnection conn = new SqlConnection(@"Database:DATABASE");
    conn.Open();

    void PopulateGrid1()
    {
        SqlCommand cmd = new SqlCommand("SELECT * FROM TABLE1");
        cmd.Connection = conn;
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        // Populate Grid1
    }

    void PopulateGrid2()
    {
        SqlCommand cmd = new SqlCommand("SELECT * FROM TABLE2");
        cmd.Connection = conn;
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        // Populate Grid2
    }
}

需要一些意见,从你们...

Need some views from you guys...

推荐答案

您应该不会离开连接打开。

You should not leave connections open..

您应该:​​

1)尽可能晚地打开连接

1) Open connections as late as possible

2)关闭连接尽快

的连接本身被返回到连接池。连接是有限的和相对昂贵的资源。您建立任何新的连接具有的究竟的相同的连接字符串就可以重新使用连接池。

The connection itself is returned to the connection pool. Connections are a limited and relatively expensive resource. Any new connection you establish that has exactly the same connection string will be able to reuse the connection from the pool.

我们强烈建议您始终
  关闭当你连接
  使用完毕,使得
  连接将被返回到
  池。您可以通过做到这一点无论是
  的关闭或Dispose方法
  Connection对象,或打开所有
  using语句中的连接
  在C#中,或Visual Using语句
  基本。连接是不
  显式关闭可能不会被添加
  或返回到池中。欲了解更多
  信息,请参阅使用语句(C#
  参考)或如何:配置的
  系统资源的Visual Basic。 参考

顺便说一句,你应该适当的包装任何实现的IDisposable 使用语句块:

BTW, you should appropriately wrap anything that implements IDisposable in a using statement block:

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

     ...

     command.ExecuteNonQuery();
 }

这篇关于为什么总是紧密数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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