1 varConstr ="server=localhost;database=data;user=sa;pwd=123456";2 using(varConnection =NewSqlConnection (constr))3 {4 connection. Open ();5 varsql =6 string. Format (7 "UPDATE dbo. Autostationdata set temperture={0} where stationnum=58365 and Datetime= ' {1} '",8.5,8 NewDateTime ( the, on, -, the, the,xx, the));//SQL statements that can be executed normally9 Ten varSQL2 =string. Format ( One "UPDATE dbo. Autostationdata set temperture={0} where stationnu=98801 and Datetime= ' {1} '",8.1, A NewDateTime ( the, on, -, the, the,xx, the));//An SQL statement that cannot be executed normally does not exist in the field Stationnu - using(varCommand =NewSqlCommand (sql,connection)) - { the varTransation = connection. BeginTransaction ();//Create transaction - Try - { -Command. Transaction =transation; + -Command.commandtext =SQL; + command. ExecuteNonQuery (); A atCommand.commandtext =sql2; - command. ExecuteNonQuery (); - - transation.commit (); - } - Catch(Exception E1) in { - Try to { + - transation. Rollback (); the } * Catch(Exception E2) $ {Panax Notoginseng - Console.Write (E2. Message); the } + A } the + } -}
Write a SQL statement that can execute normally, SQL, an error SQL statement sql2. After executing 21 lines of code, querying the whole table in the database, the query ..., directly executing the following code, because SQL2 does not execute correctly, jumps to the catch, performs a rollback, and 21 rows modifies the field value of the restore. Database this to perform a full table query is being queried .... becomes a query that was executed successfully. Starting with the execution of the first SQL statement, knowing that the commit transaction was successful, or that the rollback was successful this time the transaction exclusive of this table also embodies the atomicity of the transaction.
Simple usage of SQL Server transactions