Pergunta

We use oracle database connection and our class database access does not have a dispose or close. It interferes with something or performance of the application? I saw this example:

   string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
   OracleConnection conn = new OracleConnection(oradb); // C#
   conn.Open();
   OracleCommand cmd = new OracleCommand();
   cmd.Connection = conn;
   cmd.CommandText = "select * from departments";
   cmd.CommandType = CommandType.Text;
   OracleDataReader dr = cmd.ExecuteReader();
   dr.Read();
   label1.Text = dr.GetString(0);
   conn.Dispose();

And I realized that it opens the connection and then kills her. This is correct? Is there any other better?

I'm leaving my connection open and then ends up being closed for a while. I think that's it. This so wrong?

Foi útil?

Solução

Use the Using statement with disposable objects. In particular with any kind of connection and datareaders

string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
   conn.Open();
   cmd.Connection = conn;
   cmd.CommandText = "select * from departments";
   cmd.CommandType = CommandType.Text;
   using(OracleDataReader dr = cmd.ExecuteReader())
   {
       dr.Read();
       label1.Text = dr.GetString(0);
   }
}

Here you could read about the Using statement and why it is important. Regarding the connection and readers, you should enclose the objects with the using statement to be sure that everything is properly closed and disposed when you exit from the using block ALSO in case of exceptions

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top