Click here to Skip to main content
15,889,096 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello To all ,

i make a Website but some times when the multiple user access something from the website at sametime that gives Connection leaking or get Error.

i use like :
protected void btn_add_cat_Click(object sender, EventArgs e)
    {
        c.setcon();
        string found = "select category from ctgry where category='" + txt_cat_name.Text + "'";
        SqlDataAdapter ad1 = new SqlDataAdapter(found, c.getcon());
        DataSet ds1 = new DataSet();
        ad1.Fill(ds1);
        if (ds1.Tables[0].Rows.Count == 0)
        {
            string s1 = "select max(cat_id) from ctgry";
            SqlDataAdapter ad = new SqlDataAdapter(s1, c.getcon());
            DataSet ds = new DataSet();
            ad.Fill(ds);

            if (ds.Tables[0].Rows[0][0] == DBNull.Value)
            {
                cat_no = "1";
            }
            else
            {
                cat_no = (System.Convert.ToInt32(ds.Tables[0].Rows[0][0]) + 1).ToString();
            }

            string s = "insert into ctgry values('" + cat_no + "','" + txt_cat_name.Text + "')";
            cmd = new SqlCommand(s, c.getcon());
            cmd.ExecuteNonQuery();
}

so, by this query inside query Leak the connection or not ?
c.setcon() is My Appcode function in that i set the connection. and i use c.getcon() in Main as well as subquery , so i m not sure the error main problem is that or not ?

Please Tell me this query inside query leak the COnnection or not ?
Posted
Updated 17-Jun-12 22:38pm
v3

For each connection you need to instantiate an new sql connection and not re-use a connection unless you are using connection pooling. What is the getCon and setCon functions?

Personally you should re-write your code above to:

C#
protected void btn_add_cat_Click(object sender, EventArgs e)
    {
        sqlConnection cn = New sqlconnection("connection string");
        string found = "select category from ctgry where category='" + txt_cat_name.Text + "'";
        SqlDataAdapter ad1 = new SqlDataAdapter(found, cn );
        DataSet ds1 = new DataSet();
        ad1.Fill(ds1);
        if (ds1.Tables[0].Rows.Count == 0)
        {
            string s1 = "select max(cat_id) from ctgry";
            SqlDataAdapter ad = new SqlDataAdapter(s1, cn );
            DataSet ds = new DataSet();
            ad.Fill(ds);
 
            if (ds.Tables[0].Rows[0][0] == DBNull.Value)
            {
                cat_no = "1";
            }
            else
            {
                cat_no = (System.Convert.ToInt32(ds.Tables[0].Rows[0][0]) + 1).ToString();
            }
 
            string s = "insert into ctgry values('" + cat_no + "','" + txt_cat_name.Text + "')";
            cmd = new SqlCommand(s, cn );
            cmd.ExecuteNonQuery();
}


My other suggestion would be to move the data access into a seperate class and event class library. You should not really have this sort of thing in the code behind IMHO.

UPDATE

use this to get your connection if you want to run your code the way you have written it.

C#
public static SqlConnection GetConnection() 
        {
            try
            {
                con = new SqlConnection();
                con.ConnectionString = @"connection String";
                con.Open();
                return con;
            }
            catch (Exception ex)
            {
                //consider logging.
                //consider throwing exception. Where would a failed connection be handled?
            }          
        }


Also get rid of your set connection. Not needed.

Also if data access is an issue for you I would recommend the DataAccess blocks from Enterprise library 5. http://entlib.codeplex.com/releases[^] makes life a bit cleaner!!
 
Share this answer
 
v2
Comments
[no name] 18-Jun-12 4:48am    
getcon() is a function in APPcode:
public SqlConnection getcon()
{
return con;
}

and setcon()

public void setcon()
{
try
{
con = new SqlConnection();
con.ConnectionString = @"connection String";
if (con.State == ConnectionState.Closed)
{
con.Open();
}

}
catch (Exception e1)
{
if (con.State != ConnectionState.Closed)
con.Close();
}


}
db7uk 18-Jun-12 4:52am    
What is con? how global is it?
db7uk 18-Jun-12 4:52am    
Also what is the actual exception message?
[no name] 18-Jun-12 4:54am    
public static SqlConnection con=null
[no name] 18-Jun-12 4:59am    
Or i can do like :

protected void btn_add_cat_Click(object sender, EventArgs e)
{
c.setcon();
string found = "select category from ctgry where category='" + txt_cat_name.Text + "'";
SqlDataAdapter ad1 = new SqlDataAdapter(found, c.getcon());
DataSet ds1 = new DataSet();
ad1.Fill(ds1);
c.close();

if (ds1.Tables[0].Rows.Count == 0)
{
c.setcon();
string s1 = "select max(cat_id) from ctgry";
SqlDataAdapter ad = new SqlDataAdapter(s1, c.getcon());
DataSet ds = new DataSet();
ad.Fill(ds);

if (ds.Tables[0].Rows[0][0] == DBNull.Value)
{
cat_no = "1";
}
else
{
cat_no = (System.Convert.ToInt32(ds.Tables[0].Rows[0][0]) + 1).ToString();
}
c.close();
c.setcon();

string s = "insert into ctgry values('" + cat_no + "','" + txt_cat_name.Text + "')";
cmd = new SqlCommand(s, c.getcon());
cmd.ExecuteNonQuery();
lbl_msg.ForeColor = System.Drawing.Color.Green;
lbl_msg.Text = "Category Successfully Added";
txt_cat_name.Text = "";
txt_cat_name.Focus();
c.close();
}
else
{
lbl_msg.ForeColor = System.Drawing.Color.Red;
lbl_msg.Text = "Category Already Exits";
txt_cat_name.Focus();
}
c.close();
}
use your connection in web.config file not in appcode. and what have you written in setcon function. and as per solution 1 each time instantiate an new sql connection.

XML
<configuration>
  <connectionstrings>
    <add name="DataB" connectionstring="Data Source=.\SQLEXPRESS;<br mode=" hold=" />      AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;<br mode=" />
  </connectionstrings>
</configuration>
 
Share this answer
 
Hi,

To prevent open connection, destroy your connection when it is not in use.

you can use either using or finally block to dispose the connection. below code may be useful for you, you can also use SQLHelper[^] class.

C#
DataSet resultSet = new DataSet();
using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
{
if (parameters != default(IList<sqlparameter>) && parameters.Count > 0)
                    {
                        parameters.ToList().ForEach(p =>
                        {
                            sqlCommand.Parameters.Add(p);
                        });
                    }

                    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
                    sqlDataAdapter.SelectCommand = sqlCommand;
                    sqlDataAdapter.Fill(resultSet);
                    sqlCommand.Parameters.Clear();
}
}
return resultSet;


above function would be best to return your dataset.

Thanks
-Amit Gajjar
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900