using (SqlConnection conn = new SqlConnection()) { SqlCommand cmd = conn.CreateCommand(); //启动事务 SqlTransaction trann = conn.BeginTransaction(); //设定SqlCommand的事务和连接对象 cmd.Connection = conn; cmd.Transaction = trann; try { cmd.CommandText = "..."; cmd.ExecuteNonQuery(); trann.Commit(); } catch (Exception ex) { //数据回滚 trann.Rollback(); throw; } }
数据库中的事务 在提交之前会对涉及的表进行排它锁 长时间不释放 会导致 涉及的表无法查询;
解决办法:查询时 使用 with(nolock) 会查询出 还未被提交的操作结果
使用事务的操作时间控制在一定范围内 不要在事务中做 无关操作从而导致长时间占着资源