how to write this script
if (con.Open == true) ;
{
totalv.ExecuteNonQuery();
}
else
{
con.Open();
totalv.ExecuteNonQuery();
}
how to write this script
if (con.Open == true) ;
{
totalv.ExecuteNonQuery();
}
else
{
con.Open();
totalv.ExecuteNonQuery();
}
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();
}
}
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?