locked
How can I close all open database connections? RRS feed

  • Question

  • Hello, I need to loop through all connections to the database I am using in my app (an .mdf file) and close and dispose of them all prior to exiting my application. Could someone please show me how to do this? I am primarily using table adapters to access my DB. Thanks.
    Sunday, October 1, 2006 10:42 PM

Answers

  • the best practice would be to use the using statement - it will automatically (99% of the time) close and dispose of the connection:

     

    using theConnection as new OleDbConnection(connectionString)

       'code here for database operations

    end using

     

    or you could keep a list of connections in an array for example and loop through each and close them however you should ALWAYS  close your connections as soon as you have finished using it. Connections to databases are expensive so use it as less as possible or rather use it only when its neccessary and prepare everything before connecting/executing queries on the database.

    The above method would be the correct method to automatically dispose of the connection

    Monday, October 2, 2006 1:15 PM

All replies

  • In the closing function of your application is where you would want to initialize it...but that's about all I can help with there :\ Use a For Next method though and set Count = to the number of connections open. Then cycle through them and try the .Close()  method I guess? I've never dealt with closing of connections, so that's about all I can provide you.

    Monday, October 2, 2006 8:45 AM
  • the best practice would be to use the using statement - it will automatically (99% of the time) close and dispose of the connection:

     

    using theConnection as new OleDbConnection(connectionString)

       'code here for database operations

    end using

     

    or you could keep a list of connections in an array for example and loop through each and close them however you should ALWAYS  close your connections as soon as you have finished using it. Connections to databases are expensive so use it as less as possible or rather use it only when its neccessary and prepare everything before connecting/executing queries on the database.

    The above method would be the correct method to automatically dispose of the connection

    Monday, October 2, 2006 1:15 PM