开发者

connection problem

how to write this script

if (con.Open == true) ;
{ 
   totalv.ExecuteNonQuery();
}
else
{
   con.Open();
   totalv.ExecuteNonQ开发者_如何转开发uery();
}


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?


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜