在vb里
on error resume next
conn.begintrans....
写表一....
写表二....
if err.number > 1 then
msgbox"写数据库失败!"
conn.rollback...
else
mesgbox"成功!"
conn.commit.....
end if
在C#里怎么代替??

解决方案 »

  1.   

    //事务交给cmd了
    SqlTransaction ta;
    SqlCommand cmd=new SqlCommand;try
    {
      conn.Open();
      ta=conn.BeginTransaction();
      cmd.Transaction = ta;
      //你的操作
      ta.Commit();
      cmd.Dispose();
      conn.Close();
    }
      

  2.   

    using (SqlConnection connection = new SqlConnection(connectString))
    {
        connection.Open();    // Start a local transaction.
        SqlTransaction sqlTran = connection.BeginTransaction();    // Enlist the command in the current transaction.
        SqlCommand command = connection.CreateCommand();
        command.Transaction = sqlTran;    try
        {
            command.CommandText =
              "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
            command.ExecuteNonQuery();
            command.CommandText =
              "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
            command.ExecuteNonQuery();
            sqlTran.Commit();
            Console.WriteLine("Both records were written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("Neither record was written to database.");
            sqlTran.Rollback();
        }
    }