C#中事务处理和非事务处理方法实例分析
本文实例讲述了C#中事务处理和非事务处理方法。分享给大家供大家参考。具体如下:
C#代码如下:
StringconnectionString=ConfigurationManager.ConnectionStrings["DB_Constr"].ToString(); SqlConnectionconn=null; SqlTransactiontrans=null; try{ conn=newSqlConnection(connectionString); if(conn.State!=ConnectionState.Open)conn.Open(); //开启事务,可以指定事无级别。默认为提交才可以查询 trans=conn.BeginTransaction(); //save(conn,trans); DbUtils.commit(trans); }catch(Exceptionex){ DbUtils.rollback(trans); ClientScript.RegisterStartupScript(this.GetType(),"错误提示","<script>alert('"+StringUtil.toJsStr(ex.Message)+"');</script>"); }finally{ DbUtils.closeQuietly(conn,trans); } StringconnectionString=ConfigurationManager.ConnectionStrings["DB_Constr"].ToString(); SqlConnectionconn=null; try{ conn=newSqlConnection(connectionString); if(conn.State!=ConnectionState.Open)conn.Open(); }catch(Exceptionex){ ScriptManager.RegisterStartupScript(this,this.GetType(),"mess","<script>alert('"+StringUtil.toJsStr(ex.Message)+"')</script>",false); }finally{ DbUtils.closeQuietly(conn); }
StringUtil.cs如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; namespaceTools{ publicsealedclassStringUtil{ publicstaticboolisEmpty(Stringstr){ if(str==null)returntrue; if(str.Length==0)returntrue; if(str==String.Empty)returntrue; returnfalse; } publicstaticboolisNotEmpty(Stringstr){ return!isEmpty(str); } publicstaticStringtoJsStr(Stringstr){ str=str.Replace("'","\\'"); str=str.Replace("\r",""); str=str.Replace("\n","\\n"); returnstr; } publicstaticvoidMain(){ Console.Write(isNotEmpty(null)); Console.Read(); } } }
DbUtils.cs如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Data.SqlClient; usingSystem.Data; namespaceTools{ publicclassDbUtils{ publicstaticSqlConnectiongetConnection(stringconnectstr){ SqlConnectionconn=newSqlConnection(connectstr); if(conn.State!=ConnectionState.Open){ conn.Open(); } returnconn; } publicstaticvoidcloseQuietly(SqlConnectionconn){ try{ close(conn); }catch{} } publicstaticvoidcloseQuietly(SqlTransactiontrans){ try{ close(trans); }catch{} } publicstaticvoidclose(SqlConnectionconn){ if(conn!=null){ conn.Close(); conn.Dispose(); } } publicstaticvoidclose(SqlTransactiontrans){ if(trans!=null){ trans.Dispose(); } } publicstaticvoidcloseQuietly(SqlConnectionconn,SqlTransactiontrans){ closeQuietly(trans); closeQuietly(conn); } publicstaticvoidcommit(SqlTransactiontrans){ try{ if(trans!=null)trans.Commit(); }catch{} } publicstaticvoidrollback(SqlTransactiontrans){ try{ if(trans!=null)trans.Rollback(); }catch{} } } }
希望本文所述对大家的C#程序设计有所帮助。