/// <summary> /// 打开一个连接 /// 开启事物方法调用本方法时,要传入true /// </summary> private void OpenDB(bool isTranStart = false) { try { if (this.tran == null) { // 建立 this.conn = new SqlConnection(this.ConnectionString); // 打开连接 this.conn.Open(); // 将参数应用于此连接 if (!isTranStart) { this.cmd.Connection = this.conn; } } else { // 将参数应用于此连接 this.cmd.Connection = this.conn; // 事务用于此 this.cmd.Transaction = this.tran; } } catch (Exception e) { LogHelp.DBLog(e.Message); } }
/// <summary> /// 关闭数据库(类内用于自动关闭使用) /// 条件解释:与.连接存在,当前是状态打开,并且不是事务状态 /// </summary> private void CloseDB() { if (this.message != null) { // 参数对信息 StringBuilder paras = new StringBuilder(); for (int i = 0; i < this.cmd.Parameters.Count; i++) { paras.AppendFormat("{0}={1} | ", this.cmd.Parameters[i], this.cmd.Parameters[i].Value); } LogHelp.DBLog(string.Format("错误信息:{0} \r\n SQL语句:[ {1} ]\r\n 参数值:[ {2} ]" , this.message, this.cmd.CommandText, paras.ToString())); } if (this.conn != null && this.tran == null) { this.conn.Close(); this.conn.Dispose(); this.conn = null; this.cmd = null; } }