代码之家  ›  专栏  ›  技术社区  ›  Thorsten Kettner

如何在Oracle.ManagedDataAccess中断开连接?

  •  0
  • Thorsten Kettner  · 技术社区  · 3 年前

    我遇到了一种特殊情况,必须断开与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中,我如何确保我的旧会话在需要时关闭,并获得新会话呢?

    (我知道我可以保持旧的连接打开,然后再打开另一个,但每次打开一个额外的会话,我的程序在一段时间内可能会为一个用户打开数百个会话,当然,这应该只有一个。)

    1 回复  |  直到 3 年前
        1
  •  1
  •   Nisd    3 年前

    关闭连接时,默认情况下会返回到连接池。

    你可以打电话 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