tags:

views:

42

answers:

2
+2  Q: 

connection problem

how to write this script

if (con.Open == true) ;
{ 
   totalv.ExecuteNonQuery();
}
else
{
   con.Open();
   totalv.ExecuteNonQuery();
}
+1  A: 

Better way to do it : use of using statement with connection object

using (SqlConnection cn = new SqlConnection(connectionString))
{
    using (SqlCommand cm = new SqlCommand(commandString, cn))
    {
        cn.Open();
        cm.ExecuteNonQuery();
    }
}
Pranay Rana
+3  A: 

Well, the main problem is due to the semi-colon at the end of your if:

if (con.Open == true) ;

That's basically terminating the if statement as you've just got a block after it... which means the else has nothing to refer to. So the most minimal change would be to:

if (con.Open == true)
{ totalv.ExecuteNonQuery(); }
else
{
    con.Open();
    totalv.ExecuteNonQuery();
}

However, this is more simply written as:

if (!con.Open)
{
    con.Open();
}
totalv.ExecuteNotQuery();

Next problem - you're trying to use Open as both a property and a method. I suspect you want something like this:

if (con.State == ConnectionState.Closed)
{
    con.Open();
}
totalv.ExecuteNotQuery();

However, I would agree with Pranay that it would be better to just open and close the connection each time you need it, and let connection pooling deal with the physical network connection. Why are you dealing with a potentially-closed connection at all?

Jon Skeet
their basically i dont want to open multi connection.openits make error to my site
azeem
good you under stand what i meen thank
azeem
@azeem: You should really work on fixing that then - using the built-in connection pool is the idiomatic way to handle database connections in .NET. Keeping a single connection open is going to be really error-prone.
Jon Skeet
how to using the built-in connection poolcan you suggest me
azeem
@azeem: Exactly as per pranay's code - open the connection, close it. The actual network connection will be pooled.
Jon Skeet