【发布时间】:2014-05-06 16:04:27
【问题描述】:
这很奇怪,虽然这段代码经常执行,但它只是偶尔发生。
我让这段代码每 5 秒运行一次,它运行良好,但有时我会将异常保存在我的日志中。
异常消息:连接未关闭。连接的当前状态是打开的。
public class Log
{
static SqlConnection sqlConnection{get; set;}
public Log()
{
sqlConnection = new SqlConnection(CNN_STRING);
}
public static void Save(){
StringBuilder sb = new StringBuilder();
sb.Append("UPDATE Blabla SET ...");
SqlCommand command = new SqlCommand(sb.ToString(), sqlConnection);
try
{
if (sqlConnection.State == ConnectionState.Open) { sqlConnection.Close(); }
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Close();
}catch(Exception e){
Log.AddLog("Log ", 1, string.Concat("Query: ", sb.ToString(),
"Exception message: ", e.Message));
}
finally
{
if (sqlConnection.State == ConnectionState.Open) { sqlConnection.Close(); }
}
}
有什么线索吗?
【问题讨论】:
-
考虑使用
usingstatement来处理你的SqlConnection和SqlCommand。 -
如果连接已经打开,为什么要关闭它并重新打开它?这不是最快的,而且有成本。当您尝试再次打开连接时,很可能连接仍在关闭。
-
显示
sqlConnection的声明,是static吗?然后让它成为一个局部变量,你就完成了。 -
@TimSchmelter 它是静态的,因为方法也是静态的
-
我的意思是,它是一个静态类,有一些使用连接的静态函数
标签: c# asp.net sql asp.net-mvc exception