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 code of the chunks.
Sqlhelper:
Copy codeThe Code is as follows:
Private static SqlConnection Cnn = new SqlConnection (DbConfig. ConnectionString );
# Region checking whether SqlConnection is enabled and enabled
/// <Summary>
/// Determine whether to enable and enable SqlConnection
/// </Summary>
/// <Returns> return SqlConnection </returns>
Private static SqlConnection GetCnn ()
{
If (Cnn. State = ConnectionState. Closed)
{
Cnn. Open ();
}
Return Cnn;
}
# Endregion
# Region close database connection
/// <Summary>
/// Close the database connection
/// </Summary>
Public static void CloseCnn ()
{
Cnn. Close ();
}
# Endregion
# Region generates a transaction and starts
/// <Summary>
/// Generate a transaction and start
/// </Summary>
/// <Returns> returns this transaction </returns>
Public static SqlTransaction BeginTransaction ()
{
SqlTransaction tran = GetCnn (). BeginTransaction ();
Return tran;
}
# Endregion
DAL:
Copy codeThe Code is as follows:
Public bool test (int I, SqlTransaction tran)
{
String SQL = "insert into [test] ([item]) values (@ I )";
SqlParameter [] paras = new SqlParameter [] {new SqlParameter ("@ I", I )};
Return sqlhelper. ExecutenQuery (SQL, paras, CommandType. Text, tran)> 0;
}
BLL:
Copy codeThe Code is as follows:
UserDAO userdao = new UserDAO ();
Public bool test ()
{
Using (SqlTransaction tran = SQLHelper. BeginTransaction ())
{
Try
{
Userdao. test (2, tran );
Userdao. test (3, tran );
Tran. Commit (); return true;
}
Catch
{
Tran. Rollback ();
Return false;
}
Finally
{
SQLHelper. CloseCnn (); // closes the database connection
}
}
}
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.