来自其他类的数据库连接

问题描述 投票:2回答:3

我在程序中创建了一个类来处理数据库连接。此类包含一个名为OpenConnection()的方法,用于打开与数据库的连接。我不相信我的程序符合清洁代码的标准。这是方法。

public void OpenConnection()
{
  if(connection==null || connection.State != Connection.Open)
  {
     connection = new OracleConnection(this.connectionString);
     connection.Open();
  }
}

这种方法工作正常,但我只是想确定这是否是一种安全的方式,我不会以任何方式利用我的程序。先感谢您

更新

我还在类中添加了以下方法来关闭连接并进行处理。

    public void CloseConnection()
    {
        if (dbconnect != null | dbconnect.State != ConnectionState.Closed)
        {
            dbconnect.Close();
        }
    }

    //Here the IDsiposable method is implemented
    public void Dispose()
    {
        CloseConnection();
    }
c# sql oracle
3个回答
0
投票

由于OracleConnection实现了IDisposable,因此可能会发生资源泄漏。此外,在ConnectionState.Executing或Fetching中调用close连接可能会很糟糕,因为它将回滚所有未提交的事务。

public void OpenConnection()
{
  if (connection == null)
  {
     connection = new OracleConnection(this.connectionString);
     connection.Open();
     return;
  }

  switch (connection.State)
  {
     case ConnectionState.Closed:
     case ConnectionState.Broken:
       connection.Close();
       connection.Dispose();
       connection = new OracleConnection(this.connectionString);
       connection.Open();
       return;
  }
}

2
投票

您可以使用using子句,它将自动处理Dispose。

using (SqlConnection connection = new SqlConnection(connectionString))
    {

    connection.Open();
    SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(new SqlParameter("@EmployeeID", 123));
    command.CommandTimeout = 5;

    command.ExecuteNonQuery();

    connection.close();
}

1
投票

如果您添加this answer中建议的情况并且它是否意味着在单个线程上使用并且在非常有限的范围内,那么您编写的解决方案似乎没问题。也就是说,您似乎正准备将此类用作许多方法调用的参数,因为您需要这样做

  • 混合业务逻辑和持久性问题
  • 或者以一种其他方法不必关心是否打开连接的方式共享实例(例如,调用堆栈中的较高调用尚未调用Open)(例如,调用堆栈中的先前调用)确实打开了连接(我们称之为“环境”连接))。

这些策略中的任何一种通常都会导致麻烦。最好保持范围小,您知道连接是打开的以及何时关闭它:

using (var connection = new OracleConnection(...))
{
    connection.Open();
    ...
}

当你拥有这个小范围时,你的抽象现在没有任何价值。

© www.soinside.com 2019 - 2024. All rights reserved.