简体   繁体   中英

Was thinking about building a SqlConnection Method…is that a bad idea?

I was thinking about building a method that I could pass in the connString to in order to generate my SqlConnection .

Is that a bad idea? Is it better if I just wrap my calls in their own using (SqlConnection statements?

We had issues with another app where one of the devs was passing the connection around and keeping it open, which was causing a lot of grief.

Just wanted to ask the experts before attempting something that could lead to issues.

This is the common pattern I use and I think it's good:

using (var cn = new SqlConnection(DatabaseConnection.ConnectionStringToDb))
{
    using (var cmd = new SqlCommand("command string", cn))
    {
          // your code
    }
}

Where DatabaseConnection.ConnectionStringToDb is a static helper class property I create to fetch or store connection string.

I was thinking about building a method that I could pass in the connString to in order to generate my SqlConnection. Is that a bad idea?

It's a great idea. But Microsoft beat you to it with this constructor on SqlConnection:

http://msdn.microsoft.com/en-us/library/d7469at0.aspx

Don't keep the connection open. If you use everywhere using(SqlConnection con = new SqlConnection(...)) .Net uses connection pooling that works very fast. You can read about that here http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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