private object ExeScalarSQL(string cmdText, bool isProc) { object returnValue = null; ConnBean coSlave = null; //mssql 有 insert into ...select 操作。 if (!isOpenTrans && _IsAllowRecordSql && !cmdText.ToLower().TrimStart().StartsWith("insert ")) { coSlave = connObject.GetSlave(); } if (OpenCon(coSlave)) { try { returnValue = _com.ExecuteScalar(); recordsAffected = returnValue == null ? 0 : 1; } catch (DbException err) { string msg = "ExeScalar():" + err.Message; debugInfo.Append(msg + AppConst.BR); recordsAffected = -2; WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText))); } finally { if (!isOpenTrans) { CloseCon(); } } } return(returnValue); }
internal bool OpenCon(ConnBean cb) { try { if (!isOpenTrans && cb != null && isAllowResetConn && connObject.IsAllowSlave()) { ResetConn(cb); } Open(); if (IsAllowRecordSql) { _watch.Start(); } return(true); } catch (DbException err) { if (cb == null && connObject.BackUp != null) { connObject.InterChange(); return(OpenCon(connObject.BackUp)); //if (OpenConBak()) //{ // return true; //} } else { WriteError("OpenCon():" + err.Message); } } return(false); }
/// <summary> /// 切换数据库(修改数据库链接) /// </summary> /// <param name="dbName"></param> /// <returns></returns> internal DbResetResult ChangeDatabase(string dbName) { if (_con.State == ConnectionState.Closed)//事务中。。不允许切换 { try { if (IsExistsDbNameWithCache(dbName))//新的数据库不存在。。不允许切换 { conn = GetNewConn(dbName); _con.ConnectionString = ConnBean.RemoveConnProvider(dalType, conn); connObject = ConnObject.Create(dbName + "Conn"); connObject.Master.ConnName = dbName + "Conn"; connObject.Master.ConnString = conn; return(DbResetResult.Yes); } else { return(DbResetResult.No_DBNoExists); } } catch (Exception err) { Log.WriteLogToTxt(err); } } return(DbResetResult.No_Transationing); }
internal static ConnObject GetConnObject(string dbConn) { dbConn = string.IsNullOrEmpty(dbConn) ? AppConfig.DB.DefaultConn : dbConn; if (dbConn.EndsWith("_Bak")) { dbConn = dbConn.Replace("_Bak", ""); } if (connDicCache.ContainsKey(dbConn)) { return(connDicCache[dbConn]); } ConnBean cbMaster = GetConnBean(dbConn); if (cbMaster == null) { string errMsg = string.Format("Can't find the connection key '{0}' from web.config or app.config!", dbConn); if (dbConn == AppConfig.DB.DefaultConn) { Error.Throw(errMsg); } else { ConnBean cb = GetConnBean(AppConfig.DB.DefaultConn); if (cb != null) { cbMaster = cb.Clone();//获取默认的值。 } else { Error.Throw(errMsg); } } } ConnObject co = new ConnObject(); co.Master = cbMaster; if (dbConn != null && dbConn.Length < 32 && !dbConn.Trim().Contains(" ")) // 为configKey { ConnBean coBak = GetConnBean(dbConn + "_Bak"); if (coBak != null && coBak.ProviderName == cbMaster.ProviderName) { co.BackUp = coBak; } for (int i = 1; i < 1000; i++) { ConnBean cbSlave = GetConnBean(dbConn + "_Slave" + i); if (cbSlave == null) { break; } cbSlave.IsSlave = true; co.Slave.Add(cbSlave); } } if (!connDicCache.ContainsKey(dbConn) && co.Master.ConfigName == dbConn) // 非一致的,由外面切换后再缓存 { connDicCache.Set(dbConn, co); } return(co); }
/// <summary> /// 切换链接 /// </summary> /// <param name="cb"></param> private void ResetConn(ConnBean cb) { if (_con != null && _con.State != ConnectionState.Open && conn != cb.Conn && _IsAllowRecordSql) { conn = cb.Conn;//切换。 _con.ConnectionString = DalCreate.FormatConn(dalType, conn); } }
public ConnBean Clone() { ConnBean cb = new ConnBean(); cb.Conn = this.Conn; cb.ProviderName = this.ProviderName; cb.ConnDalType = this.ConnDalType; return(cb); }
internal void InterChange() { if (BackUp != null) { ConnBean middle = Master; Master = BackUp; BackUp = middle; } }
public ConnBean Clone() { ConnBean cb = new ConnBean(); cb.ConnName = this.ConnName; cb.ConnString = this.ConnString; cb.ConnDalType = this.ConnDalType; cb.IsOK = this.IsOK; return cb; }
protected Dictionary <string, string> GetSchemaDic(string sql, string type) { if (string.IsNullOrEmpty(sql)) { return(null); } Dictionary <string, string> dic = null; string key = ConnBean.GetHashKey(ConnName) + "_" + DataBaseName + "_" + type + "_" + StaticTool.GetHashKey(sql); #region 缓存检测 if (!string.IsNullOrEmpty(AppConfig.DB.SchemaMapPath)) { string fullPath = AppConfig.RunPath + AppConfig.DB.SchemaMapPath + key + ".json"; if (System.IO.File.Exists(fullPath)) { string json = IOHelper.ReadAllText(fullPath); dic = JsonHelper.ToEntity <Dictionary <string, string> >(json); if (dic != null && dic.Count > 0) { return(dic); } } } #endregion dic = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); IsRecordDebugInfo = false || AppDebug.IsContainSysSql; DbDataReader sdr = ExeDataReader(sql, false); IsRecordDebugInfo = true; if (sdr != null) { string tableName = string.Empty; while (sdr.Read()) { tableName = Convert.ToString(sdr["TableName"]); if (!dic.ContainsKey(tableName)) { dic.Add(tableName, Convert.ToString(sdr["Description"])); } } sdr.Close(); sdr = null; } #region 缓存设置 if (!string.IsNullOrEmpty(AppConfig.DB.SchemaMapPath) && dic != null && dic.Count > 0) { string folderPath = AppConfig.RunPath + AppConfig.DB.SchemaMapPath; if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); } string json = JsonHelper.ToJson(dic); IOHelper.Write(folderPath + key + ".json", json); } #endregion return(dic); }
/// <summary> /// 打开链接,允许切从。 /// </summary> internal bool OpenCon(ConnBean cb, AllowConnLevel leve) { try { if (cb == null) { cb = useConnBean; if (isOpenTrans && cb.IsSlave) { ResetConn(connObject.Master); } } if (!cb.IsOK) { if ((int)leve > 1 && connObject.BackUp != null && connObject.BackUp.IsOK) { ResetConn(connObject.BackUp); //重置链接。 connObject.InterChange(); //主从换位置 return(OpenCon(connObject.Master, leve)); } else if ((int)leve > 2) { //主挂了,备也挂了(因为备会替主) ConnBean nextSlaveBean = connObject.GetSlave(); if (nextSlaveBean != null) { ResetConn(nextSlaveBean);//重置链接。 return(OpenCon(nextSlaveBean, leve)); } } } else if (!isOpenTrans && cb != useConnBean && isAllowResetConn && connObject.IsAllowSlave()) { ResetConn(cb);//,_IsAllowRecordSql只有读数据错误才切,表结构错误不切? } if (useConnBean.IsOK) { Open();//异常抛 } else { WriteError("OpenCon():" + useConnBean.ErrorMsg); } if (IsAllowRecordSql) { _watch.Start(); } return(useConnBean.IsOK); } catch (DbException err) { useConnBean.IsOK = false; useConnBean.ErrorMsg = err.Message; return(OpenCon(null, leve)); } }
public ConnBean GetSlave() { if (Slave.Count > 0) { if (index == -1) { index = new Random().Next(Slave.Count); } if (times % 3 == 0) { index++; } times++; if (times == 100000) { times = 1; } if (index == Slave.Count)//2 { index = 0; } ConnBean slaveBean = Slave[index]; if (slaveBean.IsOK)//链接正常,则返回。 { return(slaveBean); } else if (Slave.Count > 1) { //int i = index + 1;//尝试一下个,。 for (int i = index + 1; i < Slave.Count + 1; i++) { if (i == Slave.Count) { i = 0; } if (i == index) { break; } if (Slave[i].IsOK) { return(Slave[i]); } } } //从全部挂了,返回主 if (Master != null && Master.IsOK) { return(Master); } else if (BackUp != null && BackUp.IsOK) { return(BackUp); } } return(null); }
protected string GetConnString(string dbName) { string newConn = AppConfig.GetConn(dbName + "Conn"); if (!string.IsNullOrEmpty(newConn)) { return(ConnBean.Create(newConn).ConnString); } return(UsingConnBean.ConnString.Replace(DataBaseName, dbName)); }
private object ExeScalarSQL(string cmdText, bool isProc) { object returnValue = null; ConnBean coSlave = null; //mssql 有 insert into ...select 操作。 bool isSelectSql = !isOpenTrans && !cmdText.ToLower().TrimStart().StartsWith("insert ");//&& _IsAllowRecordSql bool isOpenOK; if (isSelectSql) { coSlave = connObject.GetSlave(); isOpenOK = OpenCon(coSlave, AllowConnLevel.MaterBackupSlave); } else { if (useConnBean.IsSlave) // 如果是在从库,切回主库。(insert ...select 操作) { ResetConn(connObject.Master); } isOpenOK = OpenCon(); } if (isOpenOK) { try { if (!isSelectSql && useConnBean.ConnString != connObject.Master.ConnString) { recordsAffected = -2;//从库不允许执行非查询操作。 string msg = "You can't do ExeScalarSQL(with transaction or insert) on Slave DataBase!"; debugInfo.Append(msg + AppConst.BR); WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText))); } else { returnValue = _com.ExecuteScalar(); recordsAffected = returnValue == null ? 0 : 1; } } catch (DbException err) { string msg = "ExeScalar():" + err.Message; debugInfo.Append(msg + AppConst.BR); recordsAffected = -2; WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText))); } finally { if (!isOpenTrans) { CloseCon(); } } } return(returnValue); }
/// <summary> /// 切换链接 /// </summary> /// <param name="cb"></param> private bool ResetConn(ConnBean cb)//, bool isAllowReset { if (cb != null && cb.IsOK && _con != null && _con.State != ConnectionState.Open && conn != cb.ConnString) { useConnBean = cb; conn = cb.ConnString;//切换。 _con.ConnectionString = conn; return(true); } return(false); }
/// <summary> /// 切换链接 /// </summary> /// <param name="cb"></param> private bool ResetConn(ConnBean cb)//, bool isAllowReset { if (cb != null && cb.IsOK && _con != null && _con.State != ConnectionState.Open && conn != cb.Conn) { useConnBean = cb; conn = cb.Conn;//切换。 _con.ConnectionString = DalCreate.FormatConn(dalType, conn); return(true); } return(false); }
/// <summary> /// 并发操作检测 /// </summary> /// <returns></returns> //private bool CheckIsConcurrent() //{ // int waitTimes = 500;//5秒 // while (_dbOperator.ContainsKey(DataBase) && _dbOperator[DataBase] && waitTimes > -1) // { // waitTimes--; // System.Threading.Thread.Sleep(10); // if (waitTimes == 0) // { // return true; // } // } // return false; //} private DbDataReader ExeDataReaderSQL(string cmdText, bool isProc) { DbDataReader sdr = null; ConnBean coSlave = null; if (!isOpenTrans)// && _IsAllowRecordSql { coSlave = connObject.GetSlave(); } else if (useConnBean.IsSlave)// && 事务操作时,如果在从库,切回主库 { ResetConn(connObject.Master); } if (OpenCon(coSlave, AllowConnLevel.MaterBackupSlave)) { try { CommandBehavior cb = CommandBehavior.CloseConnection; if (_IsAllowRecordSql)//外部SQL,带表结构返回 { cb = isOpenTrans ? CommandBehavior.KeyInfo : CommandBehavior.CloseConnection | CommandBehavior.KeyInfo; } else if (isOpenTrans) { cb = CommandBehavior.Default;//避免事务时第一次拿表结构链接被关闭。 } sdr = _com.ExecuteReader(cb); if (sdr != null) { recordsAffected = sdr.RecordsAffected; } } catch (DbException err) { string msg = "ExeDataReader():" + err.Message; debugInfo.Append(msg + AppConst.BR); recordsAffected = -2; WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText))); } //finally //{ // if (coSlave != null) // { // ChangeConn(connObject.Master);//恢复链接。 // } //} } return(sdr); }
public DbBase(ConnObject co) { this.connObject = co; this.useConnBean = co.Master; this.conn = co.Master.Conn; this.providerName = co.Master.ProviderName; dalType = co.Master.ConnDalType; _fac = GetFactory(providerName); _con = _fac.CreateConnection(); try { _con.ConnectionString = DalCreate.FormatConn(dalType, conn); } catch (Exception err) { Error.Throw("check the connectionstring is be ok!" + AppConst.BR + "error:" + err.Message + AppConst.BR + conn); } _com = _con.CreateCommand(); if (_com != null)//Txt| Xml 时返回Null { _com.Connection = _con; _com.CommandTimeout = AppConfig.DB.CommandTimeout; } if (IsAllowRecordSql)//开启秒表计算 { _watch = new Stopwatch(); } //if (AppConfig.DB.LockOnDbExe && dalType == DalType.Access) //{ // string dbName = DataBase; // if (!_dbOperator.ContainsKey(dbName)) // { // try // { // _dbOperator.Add(dbName, false); // } // catch // { // } // } //} //_com.CommandTimeout = 1; }
private void TestOpen(object para) { ConnBean connBean = para as ConnBean; if (connBean != null && connBean.IsOK && openOKFlag == -1) { if (connBean.TryTestConn() && openOKFlag != 1) { openOKFlag = 1; _Version = connBean.Version; //设置版本号。 ResetConn(connBean); //切到正常的去。 } else { errorCount++; debugInfo.Append(connBean.ErrorMsg); } } }
private static ConnBean GetConnBean(string dbConn) { string provider; string conn = string.Format(AppConfig.GetConn(dbConn, out provider), AppConfig.WebRootPath); if (string.IsNullOrEmpty(conn)) { return(null); } ConnBean cb = new ConnBean(); cb.Conn = conn; if (string.IsNullOrEmpty(provider)) { provider = GetProvider(cb.Conn); } cb.ProviderName = provider; cb.ConnDalType = GetDalType(provider); return(cb); }
public DalBase(ConnObject co) { this.ConnObj = co; this.UsingConnBean = co.Master; _fac = GetFactory(); _con = _fac.CreateConnection(); try { _con.ConnectionString = co.Master.ConnString; } catch (Exception err) { Error.Throw("check the connectionstring is be ok!" + AppConst.BR + "error:" + err.Message + AppConst.BR + ConnName); } _com = _con.CreateCommand(); if (_com != null)//Txt| Xml 时返回Null { _com.Connection = _con; _com.CommandTimeout = AppConfig.DB.CommandTimeout; } if (IsRecordDebugInfo)//开启秒表计算 { _watch = new Stopwatch(); } //if (AppConfig.DB.LockOnDbExe && dalType == DalType.Access) //{ // string dbName = DataBase; // if (!_dbOperator.ContainsKey(dbName)) // { // try // { // _dbOperator.Add(dbName, false); // } // catch // { // } // } //} //_com.CommandTimeout = 1; }
/// <summary> /// 打开链接只切主备 /// </summary> /// <returns></returns> internal bool OpenCon() { ConnBean master = connObject.Master; if (!master.IsOK && connObject.BackUp != null && connObject.BackUp.IsOK) { master = connObject.BackUp; connObject.InterChange();//主从换位置 } if (master.IsOK || (connObject.BackUp != null && connObject.BackUp.IsOK)) { bool result = OpenCon(master, AllowConnLevel.MasterBackup); if (result && _IsAllowRecordSql) { connObject.SetNotAllowSlave(); isAllowResetConn = false; } return(result); } return(false); }
/// <summary> /// 并发操作检测 /// </summary> /// <returns></returns> //private bool CheckIsConcurrent() //{ // int waitTimes = 500;//5秒 // while (_dbOperator.ContainsKey(DataBase) && _dbOperator[DataBase] && waitTimes > -1) // { // waitTimes--; // System.Threading.Thread.Sleep(10); // if (waitTimes == 0) // { // return true; // } // } // return false; //} private DbDataReader ExeDataReaderSQL(string cmdText, bool isProc) { DbDataReader sdr = null; ConnBean coSlave = null; if (!isOpenTrans && _IsAllowRecordSql) { coSlave = connObject.GetSlave(); } if (OpenCon(coSlave)) { try { sdr = _com.ExecuteReader(isOpenTrans ? CommandBehavior.KeyInfo : CommandBehavior.CloseConnection | CommandBehavior.KeyInfo); if (sdr != null) { recordsAffected = sdr.RecordsAffected; } } catch (DbException err) { string msg = "ExeDataReader():" + err.Message; debugInfo.Append(msg + AppConst.BR); recordsAffected = -2; WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText))); } //finally //{ // if (coSlave != null) // { // ChangeConn(connObject.Master);//恢复链接。 // } //} } return(sdr); }
private static void fsy_Changed(FileSystemEventArgs e) { string json = JsonHelper.ReadJson(e.FullPath); Dictionary <string, string> dic = JsonHelper.Split(json); if (dic != null && dic.Count > 0) { foreach (KeyValuePair <string, string> item in dic) { //移除所有缓存的Key AppConfig.SetConn(item.Key, null); AppConfig.SetConn(item.Key + "_Bak", null); for (int i = 1; i < 10000; i++) { if (!AppConfig.SetConn(item.Key + "_Slave" + i, null)) { break; } } ConnObject.ClearCache(item.Key); ConnBean.ClearCache(item.Key); } } }
private static ConnBean GetConnBean(string dbConn) { string provider; string conn = string.Format(AppConfig.GetConn(dbConn, out provider), AppDomain.CurrentDomain.BaseDirectory); if (string.IsNullOrEmpty(conn)) { return null; } ConnBean cb = new ConnBean(); cb.Conn = conn; if (string.IsNullOrEmpty(provider)) { provider = GetProvider(cb.Conn); } cb.ProviderName = provider; cb.ConnDalType = GetDalType(provider); return cb; }
public ConnBean Clone() { ConnBean cb = new ConnBean(); cb.Conn = this.Conn; cb.ProviderName = this.ProviderName; cb.ConnDalType = this.ConnDalType; return cb; }
internal bool OpenCon(ConnBean cb) { try { if (!isOpenTrans && cb != null && isAllowResetConn && connObject.IsAllowSlave()) { ResetConn(cb); } Open(); if (IsAllowRecordSql) { _watch.Start(); } return true; } catch (DbException err) { if (cb == null && connObject.BackUp != null) { connObject.InterChange(); return OpenCon(connObject.BackUp); //if (OpenConBak()) //{ // return true; //} } else { WriteError("OpenCon():" + err.Message); } } return false; }