【问题标题】:Database connections: How to use c# 4.0数据库连接:如何使用 c# 4.0
【发布时间】:2013-11-08 21:54:11
【问题描述】:

初学者:

大家好 - 寻求帮助以了解我应该如何打开和关闭数据库连接。

我正在尝试解决的问题: 我有一组需要在数据访问层执行的存储过程。

我的服务调用 DA 方法 Get(Request req) 为:

public Data Get(Request request)
    {
        var data = new Data();

        data = GetData();
        data.AppleData = GetGrapeData();
        data.OrangeData = GetGrapeData();
        data.GrapeData = GetGrapeData();

        return data;
    }

其中所有getmethods getdata、getgrapedata 等都是Data 访问类中的私有方法,并且在每个方法中调用不同的SP。

现在在每种方法中我打开和关闭数据库连接为:

{  try{   
  using (var connection = new SqlConnection(connectionString)
  using (var command = connection.CreateCommand())
   {
      connection.open();
      ExecuteSP();
      connection.Close();
   }
   }catch()
     {
     }
}

现在 有什么办法可以做到这一点,所以我必须打开/关闭连接一次? 我正在尝试在每个私有方法中捕获。那样行吗? 我在上面做的方式有什么问题吗?

【问题讨论】:

  • 您可以创建一个类来管理您的连接和命令对象,并在需要时对其进行实例化。我将为您准备一个简单的示例并将其发布为答案。
  • 您确定不想使用 ORM 吗?他们已经解决了这个问题......
  • 每次你catch {},我杀了一只小猫...
  • 如果我是你,我会将 'connection.Close()' 移动到 finally。如果您在执行存储过程时遇到异常,则连接将保持打开状态,并且您将遇到严重的泄漏(您甚至不会知道它 - 因为您正在默默地失败。
  • @Haedrian 幸运的是,由于他使用 using(),他不需要手动关闭连接 - 并且“终于”已经在后台为他完成了,通过框架,stackoverflow.com/questions/278902/… ...如果我是他,我首先会摆脱 Close。之后我会来解决代码重复和 catch(){} 的问题。

标签: c# c#-4.0 data-access-layer


【解决方案1】:

是的,您只能打开一次连接。您可以使用一个类或其他东西来管理它,但对于一个简单的场景来说,这对我来说似乎有点过头了。

public Data Get(Request request)
{
    using (var connection = new SqlConnection(connectionString))
    {
        try
        {
            connection.open();

            var data = new Data();

            data = GetData(connection);
            data.AppleData = GetGrapeData(connection);
            data.OrangeData = GetGrapeData(connection);
            data.GrapeData = GetGrapeData(connection);

            return data;
        }
        finally
        {
            connection.close()
        }

    }
}

然后在调用存储过程的方法中:

private Date GetDate(SqlConnection connection)
{
    using (var command = connection.CreateCommand())
    {
        return ExecuteSP();
    }
}

您可以将异常处理放在任何您想要的位置,但如果您不打算对异常做任何事情,那么您绝对不应该捕获它。

【讨论】:

  • 我要使用这个..我能够摆脱捕获..他们真的不需要..谢谢杰夫
【解决方案2】:

使用 SQL Server,您不会希望让连接保持打开状态的时间超过您需要的时间。系统的其他部分或另一个系统可以等待它们。

其次是 ORM - EF 或 NHibernate 比大多数程序员做得更好。

【讨论】:

    【解决方案3】:

    因此,为了支持我在上面评论中提到的示例,您可以执行以下操作:

    // This is your main class.
    namespace WindowsFormsApplication1
    {
       public partial class Form1 : Form
       {
           public Form1()
           {
              InitializeComponent();
           }
    
           private void SomeMethod(object sender, EventArgs e)
           {
              ConnectToSql connToSql = new ConnectToSql(); // Instantiate the new class here.
              connToSql.SqlConnection();  // Use the new class
           }
       }   
    }
    
    // This is the class that manages your SqlCommand and connection objects
    namespace WindowsFormsApplication1
    {
       class ConnectToSql
       {
          public void SqlConnection()
          {
             try
             {
                string strConn = "Some connection string here.";
                string strCmd = "Some Sql query string here.";
    
                // Create your connection object.
                using (SqlConnection sqlConn = new SqlConnection(strConn))
                {
                    // Create your command object and pass it the connection.
                    using (SqlCommand sqlCommand = new SqlCommand(strCmd, sqlConn))
                    {
                        sqlConn.Open();
                        // Do some work here.
                        sqlConn.Close();
                    }
                }
             }
    
             catch (SqlException sqlExc)
             {
                throw;
             }
    
             catch (Exception exc)
             {
                throw;
             }
         }
    }
    

    这里有几点需要注意:

    • 这不是最好的方法。正如 cmets 中提到的,ORM 可能更适合。
    • 每次需要打开连接时,都需要使用新类,因此最好在类的顶层实例化它。
    • using 关键字将为您管理连接和命令对象,因为它们都实现了IDisposable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多