有时候程序处理的数据量比较小时,四平八稳,一切安然无恙,但数据量一大,原先潜伏的问题就暴露无遗了。
原访问数据库的代码为:
 1解决SqlTransaction用尽的问题(SQL处理超时)SqlConnection conn = new SqlConnection(strConn);
 2解决SqlTransaction用尽的问题(SQL处理超时)conn.Open();
 3解决SqlTransaction用尽的问题(SQL处理超时)SqlTransaction trans = conn.BeginTransaction();
 4解决SqlTransaction用尽的问题(SQL处理超时)try
 5解决SqlTransaction用尽的问题(SQL处理超时){
 6解决SqlTransaction用尽的问题(SQL处理超时)    CEngine.ExecuteNonQuery(trans,CommandType.Text,sql);
 7解决SqlTransaction用尽的问题(SQL处理超时)    trans.Commit();
 8解决SqlTransaction用尽的问题(SQL处理超时)}
 9解决SqlTransaction用尽的问题(SQL处理超时)catch(SqlException ex)
10解决SqlTransaction用尽的问题(SQL处理超时){
11解决SqlTransaction用尽的问题(SQL处理超时)    trans.Rollback();
12解决SqlTransaction用尽的问题(SQL处理超时)    ErrorCode = ex.Number;
13解决SqlTransaction用尽的问题(SQL处理超时)    Info = "数据操作失败:" + ex.Message;
14解决SqlTransaction用尽的问题(SQL处理超时)}
15解决SqlTransaction用尽的问题(SQL处理超时)finally
16解决SqlTransaction用尽的问题(SQL处理超时){
17解决SqlTransaction用尽的问题(SQL处理超时)    trans.Dispose();
18解决SqlTransaction用尽的问题(SQL处理超时)    conn.Close();
19解决SqlTransaction用尽的问题(SQL处理超时)
20解决SqlTransaction用尽的问题(SQL处理超时)
21解决SqlTransaction用尽的问题(SQL处理超时)
22解决SqlTransaction用尽的问题(SQL处理超时)

运行时,一旦出现数据量过大或者处理时间较长,则系统会提示出错。错误提示为“SqlTransaction已经用完;它再也不能使用。

开始时,我怀疑是跟内存有关。因为系统需要做好事务回滚的准备,每执行一条插入或修改的SQL,都要有一定的开销,数据量一大,恐怕就吃不消了。不过我查了一下SQL SERVER的资料,未见提到内存的问题。
后来想到,数据库连接SqlTransaction有个时间问题。默认是15秒。数据量大的时候,这个时间很可能就不够了。于是改为:
 1解决SqlTransaction用尽的问题(SQL处理超时)SqlConnection conn = new SqlConnection(strConn);
 2解决SqlTransaction用尽的问题(SQL处理超时)conn.Open();
 3解决SqlTransaction用尽的问题(SQL处理超时)SqlTransaction trans = conn.BeginTransaction();
 4解决SqlTransaction用尽的问题(SQL处理超时)try
 5解决SqlTransaction用尽的问题(SQL处理超时){
 6解决SqlTransaction用尽的问题(SQL处理超时)    SqlCommand cmd = new SqlCommand();
 7解决SqlTransaction用尽的问题(SQL处理超时)    cmd.CommandType = CommandType.Text;
 8解决SqlTransaction用尽的问题(SQL处理超时)    //连接时限改为300秒
 9解决SqlTransaction用尽的问题(SQL处理超时)    cmd.CommandTimeout = 300;
10解决SqlTransaction用尽的问题(SQL处理超时)    cmd.CommandText = sql;
11解决SqlTransaction用尽的问题(SQL处理超时)    cmd.Connection = conn;
12解决SqlTransaction用尽的问题(SQL处理超时)    cmd.Transaction = trans;
13解决SqlTransaction用尽的问题(SQL处理超时)    cmd.ExecuteNonQuery();
14解决SqlTransaction用尽的问题(SQL处理超时)    trans.Commit();
15解决SqlTransaction用尽的问题(SQL处理超时)}
16解决SqlTransaction用尽的问题(SQL处理超时)catch(SqlException ex)
17解决SqlTransaction用尽的问题(SQL处理超时){
18解决SqlTransaction用尽的问题(SQL处理超时)    trans.Rollback();
19解决SqlTransaction用尽的问题(SQL处理超时)    ErrorCode = ex.Number;
20解决SqlTransaction用尽的问题(SQL处理超时)    Info = "数据操作失败:" + ex.Message;
21解决SqlTransaction用尽的问题(SQL处理超时)}
22解决SqlTransaction用尽的问题(SQL处理超时)finally
23解决SqlTransaction用尽的问题(SQL处理超时){
24解决SqlTransaction用尽的问题(SQL处理超时)    trans.Dispose();
25解决SqlTransaction用尽的问题(SQL处理超时)    conn.Close();
26解决SqlTransaction用尽的问题(SQL处理超时)}

修改后在测试,问题解决:)

相关文章: