gpt4 book ai didi

c# - System.ObjectDisposedException : Cannot access a disposed object. 对象名称: 'OracleConnection' OracleConnection 对象的重用

转载 作者:行者123 更新时间:2023-11-30 14:59:53 26 4
gpt4 key购买 nike

我会为更多查询重用 OracleConnection 对象所以我写了一个简单的类:

public static class DbConnectionsManager
{
/// <summary>
///
/// </summary>
private static OracleConnection _dbConnection = null;


/// <summary>
///
/// </summary>
/// <param name="aConnectionString"></param>
/// <returns></returns>
public static OracleConnection GetDatabaseConnection(string aConnectionString)
{
try
{
if (_dbConnection == null)
{
_dbConnection = new OracleConnection(aConnectionString);
_dbConnection.Open();
return _dbConnection;
}

if (_dbConnection.State == System.Data.ConnectionState.Closed)
{
_dbConnection.ConnectionString = aConnectionString;
_dbConnection.Open();
return _dbConnection;
}

if (!_dbConnection.ConnectionString.Equals(aConnectionString))
{
_dbConnection.Close();
_dbConnection.ConnectionString = aConnectionString;
_dbConnection.Open();
return _dbConnection;
}

return null;
}
catch (Exception e)
{

return null;
}
}
}

这样我可以多次使用连接:

  using (OracleConnection connection = 
DbConnectionsManager.GetDatabaseConnection(aDbConnectionString))
{
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM MYTABLE";
command.CommandText = sql;

OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["EXAMPLE"];
Console.WriteLine(myField);
}
}

当我第一次调用该方法时,一切正常。如果我记得静态对象是 != null 的方法,但连接结果已关闭!我从不关闭连接!

当您尝试重新打开连接时出现此异常

....
if (_dbConnection.State == System.Data.ConnectionState.Closed)
{
_dbConnection.ConnectionString = aConnectionString;
_dbConnection.Open();
return _dbConnection;
}
...

错误

Message = "Cannot access a disposed object.\r\nObject name: 'OracleConnection'."

最佳答案

正如错误所说,它是一个已处置的对象。这意味着您需要删除 using ( 子句;此子句处理了您的连接对象,这就是为什么您不能在 using ( 之外使用此对象的原因。这意味着您需要创建一个类的新对象,如果你想在 using (.

之外使用它

参见:C# Using Statement

关于c# - System.ObjectDisposedException : Cannot access a disposed object. 对象名称: 'OracleConnection' OracleConnection 对象的重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16077666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com