locked
Static database connection good idea or not? RRS feed

  • Question

  • User-299388467 posted

    In an effort to speed up my pages I thought about setting up a static database connection in a subroutines page so I wouldn't have to connect and disconnect on each page, something like

    Code:
    public partial class SubsEngine : System.Web.UI.Page {
                public static MySqlConnection MySQLCon;
    public static int ConnectToMySQL() {
                      MySQLCon = new MySqlConnection(blah;");

    and then on each page I can use subs_aspx.SubsEngine.MySQLCon which would still be open.

    Is this a good idea or not? In theory if 2 people requested a page at the same time would they get an "open data reader assosciated with this connection" while the first page is loading?
    Monday, October 25, 2010 3:53 AM

Answers

  • User-1618234021 posted

    Hi

    Yes there is a possibility of error. It is not a good idea to declare connection object as static. You should follow the pattern. Have a separate class library, say DataAccessLayer and put your database logic there. Whenever any page needs db services, create object of the class and call the respective function. This will make sure you do not have concurrent connection access issues and it will not slow down your app.

    To speed up, you can see other aspect, like page structure, queries, database structure etc.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 25, 2010 4:10 AM

All replies

  • User-1618234021 posted

    Hi

    Yes there is a possibility of error. It is not a good idea to declare connection object as static. You should follow the pattern. Have a separate class library, say DataAccessLayer and put your database logic there. Whenever any page needs db services, create object of the class and call the respective function. This will make sure you do not have concurrent connection access issues and it will not slow down your app.

    To speed up, you can see other aspect, like page structure, queries, database structure etc.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 25, 2010 4:10 AM
  • User-299388467 posted

    Ok ,it good for me

    Tuesday, October 26, 2010 5:41 AM