C#数据库设计包装 [英] C# database wrapper design

查看:157
本文介绍了C#数据库设计包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计的C#数据库包装。
下面是两个选项我有:

I am designing a database wrapper for C#. Below are the two options I have:

选项A:

class DBWrapper:IDisposable
{
     private SqlConnection sqlConn;

     public DBWrapper()
     {
            sqlConn = new SqlConnection("my connection string");
            sqlConn.Open();
     }

     public DataTable RunQuery(string Sql)
     {
              implementation......
     }

     public Dispose()
     {
            if(sqlConn != null)
                   sqlConn.Close();
     }
}



选项B:

Option B:

class DBWrapper
{
     public DBWrapper()
     {            
     }

     public DataTable RunQuery(string Sql)
     {
             SqlConnection sqlConn = new SqlConnection("my connection string");
             .....implementation......
             sqlConn.Close();               
     }   
}

有关选项,当类实例打开一个连接。所以不管呼叫者多少次调用RunQuery连接时刻准备着。但是,如果应用程序在应用程序实例DBWrapper年初,连接将被刚刚打开,直到该应用程序完成无所事事。此外,它可以具有执行期间实例许多DBWrapper。所以,它有点浪费资源。

For option A connection is opened when class is instantiated. So no matter how many times the caller calls RunQuery the connection is always ready. But If the application instantiates DBWrapper early in the application, the connection will be just opened and doing nothing until the application is finished. Also, it could have many DBWrapper instantiated during the execution. So, it's kinda wasting resources.

有关B选项是没有问题的选项A有,但一个新的连接已经被打开,每次关闭主叫调用RunQuery。我不知道它多少会伤害性能。

For option B it doesn't have the problem option A has, but the a new connection has to be opened and closed everytime the caller calls RunQuery. I am not sure how much it will hurt the performance.

请分享您的经验。感谢您的阅读。

Please share your expertise. Thank you for reading.

推荐答案

有关性能方面的原因,你一定不想去与选项B(至少在情况下,我经历)
我建议选择C:

For performance reasons, you'll definitely not want to go with Option B (at least in the cases I experienced.) Let me suggest Option C:

class DBWrapper:IDisposable { private SqlConnection sqlConn;

public void EnsureConnectionIsOpen()
{
    if (sqlConn == null)
    {
      sqlConn = new SqlConnection("my connection string");
      sqlConn.Open();
    }

}

public DataTable RunQuery(string Sql)
{
    EnsureConnectionIsOpen();
    implementation......
}

public Dispose()
{
   if(sqlConn != null)
              sqlConn.Close();
}

} 

您可能会考虑使用Singleton模式以确保只有一个你DBWrapper的实例。

You might consider using the singleton pattern to make sure there is only one instance of your DBWrapper.

这篇关于C#数据库设计包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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