how to use a using block in this code?

Posted by Balajikcp8 under ASP.NET on 8/18/2012 | Points: 10 | Views : 869 | Status : [Member] | Replies : 1
public class Connection
{
private SqlConnection conn;

public Connection()
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
}

public SqlConnection Openconn()
{
if(conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
{
conn.Open();
}
return conn;
}
public void ExecuteQuery(string txtQuery)
{

SqlCommand cmd = new SqlCommand();
cmd.Connection = Openconn();
cmd.CommandText = txtQuery;
cmd.CommandTimeout = timeout;
cmd.ExecuteNonQuery();
}
public SqlConnection Close()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return conn;
}
}




Responses

Posted by: Vasanthmvp on: 8/19/2012 [Member] Starter | Points: 25

Up
0
Down

Hi, I believe this is what you are looking for..??
If you are trying to use the same with "Using" block, its a best practice to use( as far as i know).

In class:
string connstr = ConfigurationManager.ConnectionString["Conn"].ConnectionString; or .ToString(); //"Conn" is the name of the connectionstrings that we include in the web.config file.

In method Page_Load or any other:

using (sqlconnection conn = new sqlconnection(connstr))
{

if(conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
{
conn.Open(); // its better to open your connection before executing your command.
}

string sql = "write your sql query here"; // if you have a stored procedure, this is not necessary.

using (sqlcommand cmd = new sqlcommand( sql, conn))
{
// if there are any parameters, declare them and add the parameter.
// cmd.Parameters.Add(prm); if no paramerts then no need to add them.

// If you have to fill the data use some data adapter.


conn.Open();
returnvalue = cmd.ExecuteNonQuery();
conn.End();
}
}



Regards,

Awesome Coding !! :)

Balajikcp8, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response