oracle / dotnet-db-samples

.NET code samples for Oracle database developers #OracleDotNet
http://otn.oracle.com/dotnet
MIT License
413 stars 191 forks source link

Use OracleCredential Create OracleConnection The number of sessions has been increasing #242

Closed cwsheng closed 2 years ago

cwsheng commented 2 years ago

TestCode:

static string strPassword = "xxx";
static string strUserID = "xxx";
private static OracleCredential GetOracleCredential()
{
    if (string.IsNullOrWhiteSpace(strPassword) || string.IsNullOrWhiteSpace(strUserID))
    {
        throw new Exception($"{(string.IsNullOrWhiteSpace(strPassword) ? "Password" : "User ID")} Is Null");
    }
    System.Security.SecureString secPwd = new System.Security.SecureString();
    for (int i = 0; i < strPassword.Length; i++)
        secPwd.AppendChar(strPassword[i]);
    secPwd.MakeReadOnly();
    OracleCredential oraCredential = new OracleCredential(strUserID, secPwd);
    return oraCredential;
}
static void Main(string[] args)
{
    for (int i = 0; i < 5; i++)
    {
        try
        {            
            string connString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.31.52)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=bhdevcomber)));Statement Cache Size=100;";
            using (OracleConnection dbConn = new OracleConnection(connString, GetOracleCredential()))
            {
                if (dbConn.State != ConnectionState.Open)
                    dbConn.Open();
                Console.WriteLine($"No{i}");
                dbConn.Close();
                dbConn.Dispose();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

View number of sessions

image

cwsheng commented 2 years ago

ODP.NET Version:3.21.61

alexkeh commented 2 years ago

Instead of declaring a new OracleCredential every time you open a new connection

OracleCredential oraCredential = new OracleCredential(strUserID, secPwd);

reuse the existing oraCredential object once it's created. Most apps will create just one OracleCredential object per DB user. Right now, you end up creating a new OracleCredential object every time you open a connection. ODP.NET will create a NEW pool for every Open(), which is not what you intend.

cwsheng commented 2 years ago

After verification, this is correct