简体   繁体   English

C#中使用oracle连接的最佳实践

[英]Best practices with oracle connection in C #

We use oracle database connection and our class database access does not have a dispose or close. 我们使用oracle数据库连接,我们的类数据库访问没有dispose或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? 这样错了吗?

Use the Using statement with disposable objects. 将Using语句与一次性对象一起使用。 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. 在这里,您可以阅读Using语句及其重要性。 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 关于连接和读取器,您应该使用using语句将对象括起来,以确保在出现异常情况时退出using块ALSO时所有内容都已正确关闭和处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM