打印本文 打印本文 关闭窗口 关闭窗口
出现SqlTransaction 已完成;它再也无法使用的错误提示之解决方案下簈
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2921  更新时间:2009/6/9 2:33:57  文章录入:mintao  责任编辑:mintao

 批处理事务不应该把transaction事务放在for循环里,造成多个事务,这将导致错误.
应该把for放在transaction里,当成一个事务来处理,进行批处理

示例代码:

protected void btnDelete_Click(object sender, EventArgs e)  //删除
    {
        SqlServerDataBase del = new SqlServerDataBase();
        string str = "";
        SqlConnection conn = del.DBconn();
        conn.Open();
        SqlTransaction myTrans;
        myTrans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        ListBox1.Items.Clear();
        try
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)  //从GridView中选中checkbox
            {
                GridViewRow row = GridView1.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    ListBox1.Items.Add(GridView1.Rows[i].Cells[2].Text);
                    //Column 1 is the StuNumber column
                    str = GridView1.Rows[i].Cells[1].Text;  //获取删除行的StuNumber的值
                    // Response.Write(str.ToString());  
                    del.Delete("delete from StuInfo where StuNumber = '" + str + "'", null);
                    del.Delete("delete from StuSkill where StuNumber = '" + str + "'", null);//删除
                }
            }
            myTrans.Commit();
         }
        catch (Exception ex)
        {
            try
            {
                myTrans.Rollback();
            }
            catch (SqlException sqlEx)
            {
                if (del.DBconn() != null)
                {
                    Response.Write(sqlEx.GetType() + "数据库打开失败");
                    Response.Redirect("submit.htm");
                }
            }
        }
        finally
        {
            conn.Close();
        }
        BindData();
    }
}


注意:两者在使用上是有区别的!

另外在windows服务中,

windows的服务服务正常运行一段时间后,在ontimer中就无法再启动了,提示:此SqlTransaction已完成;它再也无法使用。
有可能是 timer 时间间隔 太短,造成事务太频繁!
也可能是Transaction两次提交的原因,需要注意一下timer的启用时机。

网络转载

打印本文 打印本文 关闭窗口 关闭窗口