SqlConnection as static singleton object

public class db
{
    public static string connectionString =
           WebConfigurationManager.ConnectionStrings["connectString"].ConnectionString;
    public static SqlConnection OpenConnection() 
    {
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}

      

I see a code like this and it screams WRONG! This is for ASP.NET (2.0). I understand that this is wrong.

For one, you don't have to open the SqlConnection and return it, and two, why are you stating the SqlConnection? Wouldn't it be a problem if several people try to use it at the same time?

+2


source to share


4 answers


I'm not 100% sure what the question is, but to answer this question

Wouldn't it be a problem if several people try to use it at the same time?



no, there would be no problem, because every call to OpenConnection () creates a new instance of SqlConnection. This does not mean that the code is not garbage for other reasons. I at least hope that the calls to this method look something like this:

using(var conn = db.OpenConnection())
{
  // stuff
}

      

+3


source


What static is is an OpenConnection () method that returns a connection. However, a new connection is returned each time (it is assumed that the caller will be responsible for deleting this connection object if necessary).

In other words, the given db class is nothing. Confusion can arise from not having to instantiate the db to use its OpenConnection () method (since it is static), and the rest of the code can contain multiple snippets like



myConn = db.OpenConnection();
-- then do something with myConn

      

+12


source


You can't just say "Shouts of Wrong" and then apply the term "Singleton" incorrectly. Why is single-static communication a bad approach? This you don't recreate every time, then your application can share the connection. You need to create, open and close for every frigg'n sql call that screams silly. In any case, ADO must manage this.

0


source


Connection objects must be bound to the method that executes the transaction. Sharing the same connection object between threads will damage the connection pool. See this question in SQLDataReader.GetOrdinal () rarely with IndexOutOfRange .

0


source







All Articles