Transactions: More of a processing mechanism (die)
Transactions are for additions and deletions (because they change the data)
A transaction is composed of multiple SQL statements for multiple statements, and the overall execution
The 4 characteristics of a transaction are called acid:
1, A: atomicity-----the transaction can no longer be divided (meaning that all SQL statements in a transaction are executed concurrently)
2, C: Consistency---transaction after operation, the data of the table needs to be kept to a degree of consistency (after the SQL statement operation, either succeeds or fails)
3,i: Isolation--transactions are performed separately, and one transaction is isolated from other transactions, no relationship
4,d: Persistence--but the transaction is successfully committed, then the effect on the data table is persisted
Creation of a transaction:
1, open transaction: Begin Transation
2, COMMIT TRANSACTION: Commit Transation
3, ROLLBACK TRANSACTION: ROLLBACK TRANSACTION
Note: Once a transaction is turned on, it must be committed or rolled back
If you do not commit or rollback, then you go to the data table again, you can not open the data
Eg:
Declare @error int=0//Create variable, log error message 0 to correct
Begin transaction//Open Transaction
Update bank set cmoney-=1000 where name= ' AA '
Set @[email Protected][email protected] @error
Update bank set cmoney+=1000 where name= ' BB '
Set @[email Protected][email protected] @error
if (@error <>0)//If error is not equal to 0, it indicates a mistake
ROLLBACK TRANSACTION//Rollback
Else
Commit transaction//Commit
Using transactions in VS: Steps
String constr= "server=.; User Id=sa;pwd=123;database=myschoolmoredata ";
Using (SqlConnection conn=new SqlConnection (CONSTR))
{
Create transaction, cannot new,conn point method Begtransaction ()
Sqltansaction St=null;
try{
Conn.Open ();//Open Channel
St=conn.begtransaction ();
String sql1= "Update bank set cmoney-=1000 where name= ' AA '";
String sql2= "Update bank set cmoney+=1000 where name= ' BB '";
Tells the server to use the transaction mechanism for processing
SqlCommand comm=new SqlCommand (sql2,conn,st);
Comm. ExecuteNonQuery ();
Console.WriteLine ("Ok1");
COMM.COMMANDTEXT=SQL1;
Comm. ExecuteNonQuery ();
Console.WriteLine ("Ok2");
If you're OK, you're going to commit the transaction.
St.commit ();
Console.readkey ();
}
Catch (Exception ex)//arrive here to indicate an error in the SQL statement
{
Conson.writeline (ex. Message);
St. RollBack ();//Rollback
Conson.readkey ();
}
}
SQL Server Database--"Transactions