批处理事务不应该把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的启用时机。
网络转载
Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved. 闵涛 E_mail:admin@mintao.net(欢迎提供学习资源)
鄂公网安备 42011102001154号
站长:MinTao ICP备案号:鄂ICP备11006601号-18