Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Tuesday, February 22, 2011

Create and Close Connection using singleton in c#

//Class

public class GetConnection
{
private static SqlConnection connection = null;
public static SqlConnection conn
{
get {
if (connection == null)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolsConnectionString"].ConnectionString);
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}

return connection;
}
}

public static void closeconn(SqlConnection connection)
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}

}

}

//aspx.cs Button click use Singleton Class

SqlCommand cmd = new SqlCommand("select * from students", GetConnection.conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
SqlCommand cmd1 = new SqlCommand("insert into student(Name) values(s)", GetConnection.conn);
cmd.ExecuteNonQuery();
GetConnection.closeconn(GetConnection.conn);

3 comments: