2011年10月18日 星期二

[Oracle] 測試OracleConnection是否正確關閉

  • 若Connection String沒有設定Pooling,預設是開啟(true)。

  • 查詢V$Session檢視connection建立情況:OracleConnection.Open()後會建立一connection, 查詢V$Session會出現一筆資料(需以SYSDBA身份登入)
    SELECT SID, USER#, Serial#, audsid, STATUS,
            SchemaName, OsUser, Process, Machine, Program
    FROM V$Session
    WHERE OsUser='Auser'


  • 關閉connection, 除了OracleConnection.Close()外, 也需要OracleDataReader.Close()(如果有reader的話), 否則connection無法返還至pool.
    以下例子中, 執行reader.Close()後, V$Session不再有connection的資料,
    若reader.Close()未執行, V$Session會有此connection的資料存在.
        public static void RunSample()
        {
            using (OracleConnection conn =
                new OracleConnection(
                "Data Source=dbserver;User ID=auser;Password=auser;Max Pool Size=3"))
            {
                conn.Open();

                using (OracleCommand comm =
                    new OracleCommand(Settings.GetHostsCmd, conn))
                {
                    OracleDataReader reader = comm.ExecuteReader();
                    while (reader.Read())
                    {
                        Console.WriteLine(string.Format("{0} {1} {2}",
                            reader.GetValue(0),
                            reader.GetValue(1),
                            reader.GetValue(2)));
                    }

                    //reader.Close();
                    Console.WriteLine("Done! ");
                }
            }// 離開using scope, Connection會被close.

            // 移除pool內全部的connection.
            // 若只close connection 沒有close reader,
            // connection沒有返還至pool, 因此無法移除此connection. 
            // 在V$Session可以查詢到此connection.
            OracleConnection.ClearAllPools();
        }