日期:2014-05-18 浏览次数:20769 次
SqlConnection conn = new SqlConnection("server= .\\SQLEXPRESS;uid=testuser1;pwd=test123;database=manage"); conn.Open(); SqlTransaction sqltran = conn.BeginTransaction(); try { for (int i = 0; i < 1000; i++) { SqlCommand sql = new SqlCommand("UPDATE [newplan] SET [dept] = '" + i + "' WHERE [number]='11'", conn); sql.ExecuteNonQuery(); txt_number.Text = i.ToString(); } sqltran.Commit(); } catch { sqltran.Rollback(); } finally { conn.Close(); }
SqlConnection conn = new SqlConnection("server= .\\SQLEXPRESS;uid=testuser1;pwd=test123;database=manage"); SqlCommand cmd = new SqlCommand(); conn.Open(); SqlTransaction sqltran = conn.BeginTransaction(); cmd.Connection=conn; cmd.Transaction = sqltran; try { for (int i = 0; i < 1000; i++) { cmd.CommandText = "UPDATE [newplan] SET [dept] = '" + i + "' WHERE [number]='11'"); cmd.ExecuteNonQuery(); txt_number.Text = i.ToString(); } sqltran.Commit(); } catch { sqltran.Rollback(); } finally { conn.Close(); }
------解决方案--------------------
cmd.Transaction = sqltran;
这是关键。
------解决方案--------------------
是的,要把事务赋予Command.