Tuz*_*zki 2 c# sql-server-2008-r2 executenonquery
我有用C#编写的命令行实用程序,它更新了数据库中的一些记录,然后进入循环检查其他一些东西.出于某种原因,在SQL执行后,SQL执行总是在SQL Server 2008中留下休眠等待命令会话.我可以使用SQL服务器活动监视器并运行sp_who2来确认.但SQL事务确实已成功提交.我可以通过代码中的调试以及数据库中数据记录的时间戳来说明这一点.此外,当我明确停止命令行实用程序时,将打开打开的睡眠会话.这似乎表明我的函数创建了一些SQL连接对象,在应用程序中止时它被CLR垃圾收集之前无法处理.怎么会发生这种情况?谢谢.这是代码:
bool result = false;
using (SqlConnection conn = new SqlConnection(this.Connection))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
@"if not exists (select id from pl where sj=@sj and ej=@ej and dateInactivated is null)
insert into pl(sj,ej,pf, br, tk, lastModified )
values(@sj,@ej,@pf,@br,@tk,getDate())
else
update pl set sj=@sj,ej=@ej,pf=@pf,br=@br,tk=@tk,lastModified=getDate()
where sj=@sj and ej=@ej and dateInactivated is null
";
cmd.Parameters.AddWithValue("@sj", sj);
cmd.Parameters.AddWithValue("@ej", ej);
cmd.Parameters.AddWithValue("@pf", pf);
cmd.Parameters.AddWithValue("@br", br);
cmd.Parameters.AddWithValue("@tk", tkData);
cmd.CommandTimeout = 60;
SqlTransaction trans = null;
try
{
conn.Open();
trans = conn.BeginTransaction();
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
trans.Commit();
conn.Close();
result = true;
}
catch (SqlException ex)
{
if (trans != null)
{
trans.Rollback();
}
Log.WriteLog(LogLevel.ERROR, ex.Message);
result = false;
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
}
return result;
Run Code Online (Sandbox Code Playgroud)
请注意,tk字段是xml数据库字段.