Solve the problem of SqlTransaction exhaustion (SQL processing timeout ). Sometimes the amount of data processed by the program is relatively small, stable, and safe, but the data volume is large, and the initial potential problems are exposed. The original database access code is: sometimes the data volume processed by the program is relatively small, and everything is safe, but the data volume is large, and the initial potential problems are exposed.
The original database access code is:
1 SqlConnection conn = new SqlConnection (strConn );
2conn. Open ();
3 SqlTransaction trans = conn. BeginTransaction ();
4try
5 {
6 CEngine. ExecuteNonQuery (trans, CommandType. Text, SQL );
7 trans. Commit ();
8}
9 catch (SqlException ex)
10 {
11 trans. Rollback ();
12 ErrorCode = ex. Number;
13 Info = "data operation failed:" ex. Message;
14}
15 finally
16 {
17 trans. Dispose ();
18 conn. Close ();
19}
20
21
22
During running, once the data volume is too large or the processing time is too long, the system will prompt an error. The error message is "SqlTransaction is used up; it cannot be used any more ."
At the beginning, I suspected it was related to memory. Because the system needs to prepare for transaction rollback, each execution of an inserted or modified SQL statement requires a certain amount of overhead. if the data volume is large, I am afraid it will not be enough. However, I checked the SQL SERVER information and did not see any memory problems.
Later I thought that there was a problem with the time when the database was connected to SqlTransaction. The default value is 15 seconds. When the data volume is large, this time may not be enough. So it is changed:
1 SqlConnection conn = new SqlConnection (strConn );
2conn. Open ();
3 SqlTransaction trans = conn. BeginTransaction ();
4try
5 {
6 SqlCommand cmd = new SqlCommand ();
7 cmd. CommandType = CommandType. Text;
8 // change the connection time limit to 300 seconds
9 cmd. CommandTimeout = 300;
10 cmd. CommandText = SQL;
11 cmd. Connection = conn;
12 cmd. Transaction = trans;
13 cmd. ExecuteNonQuery ();
14 trans. Commit ();
15}
16 catch (SqlException ex)
17 {
18 trans. Rollback ();
19 ErrorCode = ex. Number;
20 Info = "data operation failed:" ex. Message;
21}
22 finally
23 {
24 trans. Dispose ();
25 conn. Close ();
26}
After modification, the problem is tested and solved :)
Bytes. The original database access code is :...