C#中事务处理和非事务处理方法 C#中事务处理和非事务处理方法实例分析
罪恶的花生 人气:0想了解C#中事务处理和非事务处理方法实例分析的相关内容吗,罪恶的花生在本文为您仔细讲解C#中事务处理和非事务处理方法的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,事务处理,非事务处理,下面大家一起来学习吧。
本文实例讲述了C#中事务处理和非事务处理方法。分享给大家供大家参考。具体如下:
C#代码如下:
String connectionString = ConfigurationManager.ConnectionStrings["DB_Constr"].ToString(); SqlConnection conn = null; SqlTransaction trans = null; try { conn = new SqlConnection(connectionString); if (conn.State != ConnectionState.Open) conn.Open(); //开启事务,可以指定事无级别。默认为提交才可以查询 trans = conn.BeginTransaction(); //save(conn, trans); DbUtils.commit(trans); } catch (Exception ex) { DbUtils.rollback(trans); ClientScript.RegisterStartupScript(this.GetType(), "错误提示", "<script>alert('" + StringUtil.toJsStr(ex.Message) + "');</script>"); } finally { DbUtils.closeQuietly(conn, trans); } String connectionString = ConfigurationManager.ConnectionStrings["DB_Constr"].ToString(); SqlConnection conn = null; try { conn = new SqlConnection(connectionString); if (conn.State != ConnectionState.Open) conn.Open(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "mess", "<script>alert('"+StringUtil.toJsStr(ex.Message)+"')</script>", false); } finally { DbUtils.closeQuietly(conn); }
StringUtil.cs如下:
using System; using System.Collections.Generic; using System.Text; namespace Tools{ public sealed class StringUtil { public static bool isEmpty(String str) { if (str == null) return true; if (str.Length == 0) return true; if (str == String.Empty) return true; return false; } public static bool isNotEmpty(String str) { return !isEmpty(str); } public static String toJsStr(String str) { str = str.Replace("'", "\\'"); str = str.Replace("\r", ""); str = str.Replace("\n", "\\n"); return str; } public static void Main() { Console.Write(isNotEmpty(null)); Console.Read(); } } }
DbUtils.cs如下:
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.Data; namespace Tools{ public class DbUtils { public static SqlConnection getConnection(string connectstr) { SqlConnection conn = new SqlConnection(connectstr); if (conn.State != ConnectionState.Open) { conn.Open(); } return conn; } public static void closeQuietly(SqlConnection conn) { try { close(conn); } catch { } } public static void closeQuietly(SqlTransaction trans) { try { close(trans); } catch { } } public static void close(SqlConnection conn) { if (conn != null) { conn.Close(); conn.Dispose(); } } public static void close(SqlTransaction trans) { if (trans != null) { trans.Dispose(); } } public static void closeQuietly(SqlConnection conn, SqlTransaction trans) { closeQuietly(trans); closeQuietly(conn); } public static void commit(SqlTransaction trans) { try { if(trans!=null) trans.Commit(); } catch{ } } public static void rollback(SqlTransaction trans) { try { if (trans != null) trans.Rollback(); } catch { } } } }
希望本文所述对大家的C#程序设计有所帮助。
加载全部内容