【问题标题】:How to disconnect in Oracle.ManagedDataAccess?如何在 Oracle.ManagedDataAccess 中断开连接?
【发布时间】:2023-02-01 16:24:13
【问题描述】:

我有一种特殊情况,我必须断开并重新连接 Oracle 数据库。 (我必须检查我的连接字符串是否仍然有效,即我的密码是否仍然有效。)

不幸的是,connection.Close() 并没有关闭会话。当我重新连接新连接时,我将恢复旧会话。

这是我的代码:

using Oracle.ManagedDataAccess.Client;

...

string connectionString = "Data Source=mydb;User Id=myuser;Password=\"mypwd\";";

using (OracleConnection connection = new OracleConnection())
{
  connection.ConnectionString = connectionString;
  connection.Open();
  using (OracleCommand command = new OracleCommand("DBMS_APPLICATION_INFO.SET_CLIENT_INFO", connection))
  {
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("input", OracleDbType.Varchar2, "hello", System.Data.ParameterDirection.Input);
    command.ExecuteNonQuery();
  }
  connection.Close();
}

using (OracleConnection connection = new OracleConnection())
{
  connection.ConnectionString = connectionString;
  connection.Open();
  using (OracleCommand command = new OracleCommand("DBMS_APPLICATION_INFO.READ_CLIENT_INFO", connection))
  {
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("output", OracleDbType.Varchar2, 4000, "", ParameterDirection.Output);
    command.ExecuteNonQuery();
    string clientInfo = command.Parameters["output"].Value.ToString();
    MessageBox.Show(clientInfo);
  }
  connection.Close();
}

此代码会导致显示“hello”的消息框,尽管我的新会话从未设置会话变量,因此一定不知道该值。

那么,我如何在 Oracle.ManagedDataAccess 中确保我的旧会话关闭并在我需要时获得新会话?

(我知道我可以保持我的旧连接打开然后打开另一个,但是通过每次打开一个额外的会话,我的程序最终可能会在某个时间为单个用户打开数百个打开的会话,而它应该只有一个,当然。)

【问题讨论】:

    标签: c# oracle-manageddataaccess


    【解决方案1】:

    关闭连接时,默认返回连接池。

    您可以调用ClearPool 从池中删除所有具有特定连接字符串的连接。

    // Create a new connection object
    OracleConnection connNew = new OracleConnection(strConn);
    
    // Clears the pool associated with Connection 'connNew'
    // Since the same connection string is set for both the connections,
    // connNew and conn, they will be part of the same connection pool.
    // We need not do an Open() on the connection object before calling
    // ClearPool
    OracleConnection.ClearPool (connNew);
    

    https://docs.oracle.com/database/121/ODPNT/OracleConnectionClass.htm#CHDFJBAF

    【讨论】:

      猜你喜欢
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 2011-02-03
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      相关资源
      最近更新 更多