打开和关闭数据库连接 [英] Opening and closing database connection

查看:108
本文介绍了打开和关闭数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每天8个小时,每毫秒对MySQL数据库进行一次Timer轮询,想知道是否应该在每次连接后打开和关闭db,还是应该保持连接打开直到整个过程完成?

保持每毫秒重新建立连接的效率似乎很低,但我只是在猜测.我回想起使用连接池来读取MySQL内容的情况,实际上并没有处理连接,而是将其重新添加到连接池中,但是我对此不太确定...

有人可以给我启发一下吗?

-Dee

解决方案

如果每毫秒创建一次连接,最好保持连接打开.上面的答案是,如果您想每秒连接数据库,那么最好保持连接打开而不是每秒连接数据库.这样可以节省您的系统资源和代码行.


我建​​议在需要时使用惰性初始化模式()打开连接并保持打开状态.像这样的东西:

  class  DatabaseWrapper {
   
    内部 DatabaseWrapper(/*   ... */){
       //  ... 
       fConnection =  //  ... 
       //  ... 
    }

    /*   ... */连接连接{//  SqlConnection,OleDbConnection等
           获取 {
              如果(fConnection.State!= System.Data.ConnectionState.Open)
                 fConnection.Open();
              返回 fConnection;
           }
    }

    /*   ... */ SomeMethod(){
        // 在此,将保证打开连接,但只能打开一次:
        /*   ... */命令命令=  /*   ... */ Command(query,Connection); //  SqlCommand,OleDbCommand,等等... 
    }

    /*   ... */连接fConnection; //  SqlConnection,OleDbConnection等
} 



—SA


Polling MySQL database with Timer class every millisecond for 8 hrs a day, wanted to know if I should open and close the db after each connection or should I just leave the connection open until the total process is complete?

Seems pretty inefficient to keep re-establishing a connection every millisecond but I''m only guessing. I recall reading something along the lines of the MySQL using connection pooling and actually not disposing of the connection but adding it back to the connection pool but I''m not exactly sure on that...

Can someone please enlighten me on this one?

-Dee

解决方案

If the connection is created every millisecond, it would be better to keep connection open..


Exactly as the above answer if you want to connect with the DataBase in every second then it is better to keep conncetion open rather than connecting with DataBase in every Second.It saves you system Resources, line of code.


I would advise to use lazy initialization pattern () to open a connection when required and keep it open. Something like this:

class DatabaseWrapper {
   
    internal DatabaseWrapper(/*...*/) {
       //...
       fConnection = new //...
       //...
    }

    /*...*/Connection Connection { // SqlConnection, OleDbConnection, whatever
           get {
              if (fConnection.State != System.Data.ConnectionState.Open)
                 fConnection.Open();
              return fConnection;
           }
    }

    /*...*/ SomeMethod() {
        // here, connection will be guaranteed to open, but only once:
        /*...*/Command command = new /*...*/Command(query, Connection); // SqlCommand, OleDbCommand, whatever...
    }

    /*...*/Connection fConnection; // SqlConnection, OleDbConnection, whatever
}



—SA


这篇关于打开和关闭数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆