When a student registers for the data center charging system. The registration function requires writing records to the Student table, Card table, and ChargeRecord table.
At that time, there was a confusion when dealing with this problem. What should I do if the Student table is successfully inserted when I insert data to the database, and the Card table or ChargeRecord table is not successfully inserted? Does this cause data inconsistency?
Later, I checked my notes and found that there was a consistent processing mechanism for transactions in ADO. Net. Transactions have four features: atomicity, consistency, isolation, and durability. The data consistency can be ensured through the "transaction" processing mechanism.
In ADO. Net, there are also "local transaction processing" and "Distributed Transaction processing ". The "local transaction processing" operation is a database, and the "Distributed Transaction processing" operation is performed on multiple databases, which is the difference between them.
Because we only use one database this time, we will start learning from "local transaction processing.
Let me use a Demo to explain it to you:
Using System; using System. collections. generic; using System. linq; using System. text; using System. data; using System. data. sqlClient; namespace TransactionDemo {class Program {static void Main (string [] args) {// declare a string-type array string [] categoryName = new string [] {"aaa ", "bbb", "ccc", "ddd", "eee"}; // string strCon = "Data Source = .; initial Catalog = test; uid = sa; pwd = 123456; "; using (SqlConnection con = new SqlConnection (strCon) {using (SqlCommand cmd = con. createCommand () {con. open (); // create a transaction SqlTransaction trans = con. beginTransaction (); cmd. transaction = trans; try {// Insert the data in the array to the bID field for (int I = 0; I <categoryName. length; I ++) {string ins = "insert into B (bID) values ('" + categoryName [I] + "')"; cmd. commandText = ins; cmd. executeNonQuery ();} // submit the transaction trans. commit ();} catch (Exception ex) {Console. writeLine (ex. message); // if the transaction is not completed, it will be rolled back to the initial state trans. rollback ();}}}}}}If all data is successfully executed, the data in the array is inserted into the database. If any data in the array fails to be executed successfully, all data is inserted and rolled back to the initial state.
This scenario tells us to think more and read others' blogs. Through thinking, we can find problems that others have not noticed. By reading these questions, we can learn a lot of typical solutions. Let us all stand on the shoulders of giants. We don't have to think about it for a long time before we find that such problems already have solutions.
I hope my explanation will be helpful to you.