I know more. net, there are two ways to execute transactions. One is automatic transactions, which is quite simple to use, but you need to configure the server. If you are using a Web shared host, that is to say, if you do not have the permission to configure your own server, you do not need to use it. Next let's talk about it. the most common transaction sqltransaction in. net.
I have been in touch with Layer 3 for a while. I know the level is average. I was wondering how to use transactions in Layer 3 some time ago. Where should I put them? Sqlherper? Dal? Bll ?. Then I went crazy About Baidu, but it was unsuccessful for several times (because it was a small project, and it didn't matter if there was no transaction). Today I checked it again and read it for discussion on csdn, bytes. My idea is to write the transaction logic in the business logic layer. The database processing is still in sqlhelper, and The bll layer accesses the Dal through the sqltransaction passed value, and then sqlhelper. Next is the multipartCode.
Sqlhelper:
1 Private Static Sqlconnection CNN = New Sqlconnection (dbconfig. connectionstring );
2
3 # Region Check whether sqlconnection is enabled and enabled
4 /// <Summary>
5 /// Check whether sqlconnection is enabled and enabled
6 /// </Summary>
7 /// <Returns> Return sqlconnection </Returns>
8 Private Static Sqlconnection getcnn ()
9 {
10 If (CNN. State = connectionstate. Closed)
11 {
12 CNN. open ();
13 }
14 Return CNN;
15 }
16 # Endregion
17
18 # Region Close database connection
19 /// <Summary>
20 /// Close database connection
21 /// </Summary>
22 Public Static Void Closecnn ()
23 {
24 CNN. Close ();
25 }
26 # Endregion
27
28 # Region Generate a transaction and start
29 /// <Summary>
30 /// Generate a transaction and start
31 /// </Summary>
32 /// <Returns> Returns this transaction </Returns>
33 Public Static Sqltransaction begintransaction ()
34 {
35 Sqltransaction TRAN = getcnn (). begintransaction ();
36 Return Tran;
37 }
38 # Endregion
Dal:
1 Public Bool Test ( Int I, sqltransaction TRAN)
2 {
3 String SQL = " Insert into [test] ([item]) values (@ I) " ;
4 Sqlparameter [] paras = New Sqlparameter [] { New Sqlparameter ( " @ I " , I )};
5 Return Sqlhelper. executenquery (SQL, paras, commandtype. Text, Tran)> 0 ;
6 }
Bll:
1 Userdao = New Userdao ();
2
3
4 Public Bool Test ()
5 {
6 Using (Sqltransaction TRAN = sqlhelper. begintransaction ())
7 {
8 Try
9 {
10 Userdao. Test ( 2 , Tran );
11 Userdao. Test ( 3 , Tran );
12 Tran. Commit (); Return True ;
13 }
14 Catch
15 {
16
17 Tran. rollback ();
18 Return False ;
19 }
20 Finally
21 {
22 Sqlhelper. closecnn ();// Close database connection
23 }
24 }
25 }
The above code is passed in this test. If you want to use it in a real project, Please modify the code before using it. The level is average. If you cannot write it, please forgive me. Thank you for your guidance.