Sql connection helper

Hi everyone,

This is my first post here, so I will start with an very simple and quite useful example of the SQL connection object helper. When using ado.net it basically helps reducing amount of code needed to instantiate connection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Connection
{
    public Connection()
    {
 
    }
 
    public static SqlConnection Current
    {
        get
        {
            SqlConnection con = null;
            if (HttpContext.Current.Session["sqlconnection"] == null)
            {
                HttpContext.Current.Session["sqlconnection"] = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
            }
            con = (SqlConnection)HttpContext.Current.Session["sqlconnection"];
            if (con.State != ConnectionState.Open) { con.Open(); }
            return con;
        }
 
    }
}

All you need to do is to use Current property of that object to create connection instance or reuse it if already created eg.

1
2
3
4
5
6
7
8
9
10
11
12
using (SqlCommand cmd = new SqlCommand("getData", Connection.Current))
{
       cmd.CommandType = CommandType.StoredProcedure;
 
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
           while (reader.Read())
           {
               //to do get data
           }
        }
 }
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...