日期:2014-05-18  浏览次数:20769 次

C# winform程序 事务处理
各位大侠给看下,下面的代码有什么问题,现在现象是我去掉 
SqlTransaction sqltran = conn.BeginTransaction(); sqltran.Commit(); sqltran.Rollback();这三句后程序可以正常,但是加上这三句后就不行了,事务处理要怎么来写请各位指教!!!
 
C# code
 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();
            }


------解决方案--------------------
C# code

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.