代碼說明:
1.本類對SqlHelper.cs 進一步封裝。
2.Configurations.SQLSERVER_CONNECTION_STRING 替換成自己的連接字符串就行了。
UserInfoAction.cs
public class UserInfoAction : SqlDAL { /// <summary> /// 添加用戶 /// </summary> public void Add(UserInfo user) { StringBuilder sb = new StringBuilder(); sb.Append("UPDATE [UserInfo] SET Password='"); sb.Append(user.PassWord); sb.Append("' WHERE UID="); sb.Append(user.UID); ExecuteNonQuery(sql); } }
如果我們要加入事務,通常的辦法就是在方法內try、catch然後Commit、Rollback,缺點就不說了,下面我會邊貼代碼邊講解,力圖大家也能掌握這種方法: )
先貼前面兩個被我修改的類
SqlDAL.cs
public abstract class SqlDAL : ContextBoundObject { private SqlTransaction _SqlTrans; /// <summary> /// 僅支持有事務時操作 /// </summary> public SqlTransaction SqlTrans { get { if (_SqlTrans == null) { //從上下文中試圖取得事務 object obj = CallContext.GetData(TransactionAop.ContextName); if (obj != null && obj is SqlTransaction) _SqlTrans = obj as SqlTransaction; } return _SqlTrans; } set { _SqlTrans = value; } } #region ConnectionString private SqlConnectionStringBuilder _ConnectionString = null; /// <summary> /// 字符串連接 /// </summary> public virtual SqlConnectionStringBuilder ConnectionString { get { if (_ConnectionString == null || string.IsNullOrEmpty(_ConnectionString.ConnectionString)) { _ConnectionString = new SqlConnectionStringBuilder(Configurations.SQLSERVER_CONNECTION_STRING); } return _ConnectionString; } set { _ConnectionString = value; } } #endregion #region ExecuteNonQuery public int ExecuteNonQuery(string cmdText) { if (SqlTrans == null) return SqlHelper.ExecuteNonQuery(ConnectionString.ConnectionString, CommandType.Text, cmdText); else return SqlHelper.ExecuteNonQuery(SqlTrans, CommandType.Text, cmdText); } public int ExecuteNonQuery(string cmdText, CommandType type) { if (SqlTrans == null) return SqlHelper.ExecuteNonQuery(ConnectionString.ConnectionString, type, cmdText); else return SqlHelper.ExecuteNonQuery(SqlTrans, type, cmdText); } public int ExecuteNonQuery(string cmdText, CommandType type, params SqlParameter[] cmdParameters) { if (SqlTrans == null) return SqlHelper.ExecuteNonQuery(ConnectionString.ConnectionString, type, cmdText, cmdParameters); else return SqlHelper.ExecuteNonQuery(SqlTrans, type, cmdText, cmdParameters); } #endregion }