DBProxy.cs 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957
  1. using System;
  2. using System.Collections;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Data.OleDb;
  6. using System.Data.OracleClient;
  7. using System.Xml;
  8. using System.IO;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Runtime.Remoting.Lifetime;
  12. using System.Data.Common;
  13. using System.Reflection;
  14. using System.Configuration;
  15. using Core.Mes.Common;
  16. using System.Runtime.Serialization.Formatters.Binary;
  17. using System.Runtime.Serialization;
  18. namespace STMes
  19. {
  20. /// <summary>
  21. /// DBProxy 的摘要说明。
  22. /// </summary>
  23. public class DBProxy : MarshalByRefObject, IDisposable
  24. {
  25. private static Hashtable _dataProviderNameList = Hashtable.Synchronized(new Hashtable(5));
  26. private static Hashtable _dataProviderTypeList = Hashtable.Synchronized(new Hashtable(5));
  27. private CoreWriteLogFile cwl = new CoreWriteLogFile();
  28. private CoreWriteLogFile cwl_sql = new CoreWriteLogFile("SQL");
  29. public DBProxy()
  30. {
  31. InitDBProxy();
  32. }
  33. private bool _isLogging = false;
  34. public void SetLogging(bool _log)
  35. {
  36. _isLogging = _log;
  37. cwl_sql.StartLogging(_log);
  38. }
  39. public void InitDBProxy()
  40. {
  41. AddDataProvider(new DataProvider.SqlDataProvider());
  42. AddDataProvider(new DataProvider.OleDbDataProvider());
  43. AddDataProvider(new DataProvider.OdbcDataProvider());
  44. AddDataProvider(new DataProvider.OracleDataProvider());
  45. AddDataProvider(new DataProvider.ODPDataProvider());
  46. Console.WriteLine("创建数据库代理DBProxy...\n");
  47. //从数据库配置文件中读取数据库连接信息
  48. ReadDbConnectionInfo(@"MesDB.cfg");
  49. //预先创建所有连接...
  50. CreateAllConnections();
  51. _connLifeTimeA = int.Parse(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["connLifeTimeA"].Value.ToString().ToLower());
  52. _connLifeTimeB = int.Parse(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["connLifeTimeB"].Value.ToString().ToLower());
  53. _connLifeTimeC = int.Parse(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["connLifeTimeC"].Value.ToString().ToLower());
  54. //创建一个线程,用来定时清除已经断开连接的DBManager
  55. #region 原来代码 maliang 2011-10-19
  56. /*
  57. _checkConnThread = new Thread(new ThreadStart(CheckConnActive));
  58. _checkConnThread.Start();
  59. _fixConnThread = new Thread(new ThreadStart(FixConnections));
  60. _fixConnThread.Start();
  61. */
  62. #endregion
  63. #region 变更代码 maliang 2011-10-19
  64. _ConnectionsListenerThread = new Thread(new ThreadStart(ConnectionsListener));
  65. _ConnectionsListenerThread.Start();
  66. #endregion
  67. _init = true;
  68. _reference++;
  69. }
  70. //没有显示调用Dispose()时调用
  71. ~DBProxy()
  72. {
  73. Dispose(false);
  74. }
  75. #region IDisposable 成员
  76. public void Dispose()
  77. {
  78. Dispose(true);
  79. GC.Collect();
  80. }
  81. protected virtual void Dispose(bool disposing)
  82. {
  83. _reference--;
  84. if (disposing == true)
  85. {
  86. //释放受控资源
  87. }
  88. //释放未受控资源
  89. //回滚所有DBManager事务
  90. foreach (DictionaryEntry it in _transList)
  91. {
  92. TransInfo info = (TransInfo)it.Value;
  93. IDbConnection conn = info.dbConnection;
  94. try
  95. {
  96. info.dbTransaction.Rollback();
  97. }
  98. catch (Exception)
  99. {
  100. }
  101. if (_reference == 0)
  102. {
  103. //关闭数据库连接
  104. foreach (DictionaryEntry it1 in _connList)
  105. {
  106. Hashtable ht1 = (Hashtable)it1.Value;
  107. foreach (DictionaryEntry it2 in ht1)
  108. {
  109. Hashtable ht2 = (Hashtable)it2.Value;
  110. foreach (DictionaryEntry it3 in ht2)
  111. {
  112. ArrayList arr = it3.Value as ArrayList;
  113. foreach (object obj in arr)
  114. {
  115. IDbConnection db = (IDbConnection)obj;
  116. db.Close();
  117. }
  118. }
  119. }
  120. }
  121. }
  122. }
  123. // 关闭线程
  124. try
  125. {
  126. if (_checkConnThread != null)
  127. _checkConnThread.Abort();
  128. }
  129. catch (Exception) { }
  130. try
  131. {
  132. if (_fixConnThread != null)
  133. _fixConnThread.Abort();
  134. }
  135. catch (Exception) { }
  136. }
  137. #endregion
  138. //返回由DBProxy为每个DBManager对象分配的ID
  139. public long GetDBManagerID()
  140. {
  141. lock (_dbManagerID)
  142. {
  143. ++_dbManagerID[0];
  144. if (_dbManagerID[0] > 3000000)
  145. _dbManagerID[0] = 1;
  146. return _dbManagerID[0];
  147. }
  148. }
  149. //设置DBManager对应的数据库信息
  150. public void SetDbInfo(long dbManagerID, string dbName, string priority)
  151. {
  152. if (_dbList.Contains(dbManagerID))
  153. {
  154. _dbList.Remove(dbManagerID);
  155. }
  156. ArrayList arr = new ArrayList();
  157. arr.Add(dbName);
  158. arr.Add(priority);
  159. _dbList.Add(dbManagerID, arr);
  160. }
  161. //获取数据库类型,用字符串"SQLServer","Oracle", "OleDb"分别表示不同类型的数据库
  162. public string GetDbType(string name, out string err)
  163. {
  164. err = "";
  165. //未找到该数据库对应的配置信息
  166. if (_dbConfigInfo.Contains(name) == false)
  167. {
  168. err = "未找到指定的数据库";
  169. return "";
  170. }
  171. //获取该数据库对应优先级的配置信息
  172. DBConnectionInfo dbInfo = (DBConnectionInfo)_dbConfigInfo[name];
  173. return dbInfo.dbType;
  174. }
  175. private DataSet SetSerializationType(DataSet _dataset)
  176. {
  177. if (_dataset != null)
  178. _dataset.RemotingFormat = SerializationFormat.Binary;
  179. return _dataset;
  180. }
  181. #region"数据操作"
  182. //执行带参数的SQL语句,返回DataSet
  183. //事务处理
  184. public DataSet ExecuteQuery(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, out string err)
  185. {
  186. return ExecuteQueryBase(dbName, priority, guid, Sql, cmdType, Params, Values, out err);
  187. }
  188. private DataSet ExecuteQueryBase(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, out string err)
  189. {
  190. err = "";
  191. DataSet ds = new DataSet();
  192. //获取数据库连接...
  193. IDbConnection conn = null;
  194. IDbTransaction trans = null;
  195. if (guid != null)
  196. {
  197. //如果是事务
  198. if (_transList.Contains(guid))
  199. {
  200. TransInfo info = (TransInfo)_transList[guid];
  201. conn = info.dbConnection;
  202. trans = info.dbTransaction;
  203. //如果事务已经失效,则返回
  204. if (trans.Connection == null)
  205. {
  206. err = "事务已经失效!";
  207. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQueryBase");
  208. return SetSerializationType(ds);
  209. }
  210. }
  211. else
  212. {
  213. err = "未找到请求的事务!";
  214. cwl.WriteLog("未找到请求的事务", LogInfoLevel.Error, "ExecuteQuery", "ExecuteQueryBase");
  215. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQueryBase");
  216. return SetSerializationType(ds);
  217. }
  218. }
  219. try
  220. {
  221. ArrayList outArys = null;
  222. ExecuteQueryFunc(conn, trans, Sql, cmdType, Params, Values, ref outArys);
  223. }
  224. catch (Exception ex)
  225. {
  226. err = ex.Message;
  227. cwl.WriteLog(err, LogInfoLevel.Error, "ExecuteQuery", "ExecuteQueryBase");
  228. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQueryBase");
  229. }
  230. return SetSerializationType(ds);
  231. }
  232. public DataSet ExecuteQuery(string dbName, string priority, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, out string err)
  233. {
  234. return this.ExecuteQuery(dbName, priority, Sql, cmdType, Params, Values, out err, false);
  235. }
  236. //非事务处理
  237. public DataSet ExecuteQuery(string dbName, string priority, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, out string err, bool ifDBLink)
  238. {
  239. if (ifDBLink)
  240. {
  241. return ExecuteQueryDBLink(dbName, priority, Sql, cmdType, Params, Values, out err);
  242. }
  243. else
  244. {
  245. err = "";
  246. DataSet ds = new DataSet();
  247. //获取数据库连接...
  248. IDbConnection conn = GetDbConnection(dbName, priority, Sql);
  249. try
  250. {
  251. ArrayList outArys = null;
  252. ds = ExecuteQueryFunc(conn, null, Sql, cmdType, Params, Values, ref outArys);
  253. }
  254. catch (Exception ex)
  255. {
  256. err = ex.Message;
  257. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  258. }
  259. finally
  260. {
  261. ReleaseDbConnection(dbName, priority, conn, Sql);
  262. }
  263. return SetSerializationType(ds);
  264. }
  265. }
  266. //非事务处理
  267. private DataSet ExecuteQueryDBLink(string dbName, string priority, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, out string err)
  268. {
  269. err = "";
  270. DataSet ds = new DataSet();
  271. //获取数据库连接...
  272. IDbConnection conn = null;
  273. IDbTransaction trans = null;
  274. conn = GetDbConnection(dbName, priority, Sql);
  275. if (conn == null)
  276. {
  277. err = "获取数据库连接失败!";
  278. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQueryDBLink");
  279. return SetSerializationType(ds);
  280. }
  281. try
  282. {
  283. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  284. IDbCommand command = conn.CreateCommand();
  285. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  286. ((IDbDataAdapter)adapter).SelectCommand = command;
  287. trans = conn.BeginTransaction();
  288. command.CommandText = Sql;
  289. command.CommandType = cmdType;
  290. command.Transaction = trans;
  291. //给所有的参数赋值
  292. if (Params != null && Values != null)
  293. {
  294. for (int i = 0; i < Params.Length; i++)
  295. {
  296. command.Parameters.Add(Params[i]);
  297. ((IDbDataParameter)command.Parameters[i]).Value = Values[i];
  298. }
  299. }
  300. adapter.Fill(ds);
  301. command.Transaction.Commit();
  302. command.CommandText = "begin dbms_session.close_database_link('XGCX');end;";
  303. command.ExecuteNonQuery();
  304. cwl_sql.WriteLog(adapter.SelectCommand.CommandText, LogInfoLevel.Message, "ExecuteQuery", "ExecuteQueryDBLink");
  305. }
  306. catch (Exception ex)
  307. {
  308. err = ex.Message;
  309. if (trans != null)
  310. {
  311. trans.Rollback();
  312. }
  313. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQueryDBLink");
  314. }
  315. finally
  316. {
  317. ReleaseDbConnection(dbName, priority, conn, Sql);
  318. }
  319. return SetSerializationType(ds);
  320. }
  321. //执行带参数的SQL语句,返回DataSet
  322. //事务处理
  323. public DataSet ExecuteQuery(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions, bool[] IsNullables, string[] SourceColumns, DataRowVersion[] SourceVersions, object[] Values, ref ArrayList OutputValues, out string err)
  324. {
  325. err = "";
  326. DataSet ds = null;
  327. ds = new DataSet();
  328. //获取数据库连接...
  329. IDbConnection conn = null;
  330. IDbTransaction trans = null;
  331. //如果是事务
  332. if (_transList.Contains(guid))
  333. {
  334. //Console.WriteLine("事务:执行数据库操作{0}...\n", Sql);
  335. TransInfo info = (TransInfo)_transList[guid];
  336. conn = info.dbConnection;
  337. trans = info.dbTransaction;
  338. //如果事务已经失效,则返回
  339. if (trans.Connection == null)
  340. {
  341. err = "事务已经失效!";
  342. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  343. return SetSerializationType(ds);
  344. }
  345. }
  346. else
  347. {
  348. err = "未找到请求的事务!";
  349. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  350. return SetSerializationType(ds);
  351. }
  352. try
  353. {
  354. IDataParameter[] Params = CreateParams(conn, ParameterNames, DbTypes, Directions);
  355. ds = ExecuteQueryFunc(conn, trans, Sql, cmdType, Params, Values, ref OutputValues);
  356. }
  357. catch (Exception ex)
  358. {
  359. err = ex.Message;
  360. trans.Rollback();
  361. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  362. }
  363. return SetSerializationType(ds);
  364. }
  365. public DataSet ExecuteQuery(string dbName, string priority, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions, bool[] IsNullables, string[] SourceColumns, DataRowVersion[] SourceVersions, object[] Values, ref ArrayList OutputValues, out string err)
  366. {
  367. return ExecuteQuery(dbName, priority, Sql, cmdType, ParameterNames, DbTypes, Directions, IsNullables, SourceColumns, SourceVersions, Values, ref OutputValues, out err, false);
  368. }
  369. //非事务处理
  370. public DataSet ExecuteQuery(string dbName, string priority, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions, bool[] IsNullables, string[] SourceColumns, DataRowVersion[] SourceVersions, object[] Values, ref ArrayList OutputValues, out string err, bool ifDBLink)
  371. {
  372. err = "";
  373. DataSet ds = null;
  374. ds = new DataSet();
  375. //获取数据库连接...
  376. IDbConnection conn = null;
  377. //获取数据库连接
  378. conn = GetDbConnection(dbName, priority, Sql);
  379. try
  380. {
  381. IDataParameter[] Params = CreateParams(conn, ParameterNames, DbTypes, Directions);
  382. ds = ExecuteQueryFunc(conn, null, Sql, cmdType, Params, Values, ref OutputValues);
  383. }
  384. catch (Exception ex)
  385. {
  386. err = ex.Message;
  387. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  388. }
  389. finally
  390. {
  391. //释放连接
  392. ReleaseDbConnection(dbName, priority, conn, Sql);
  393. }
  394. return SetSerializationType(ds);
  395. }
  396. private IDataParameter[] CreateParams(IDbConnection conn, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions)
  397. {
  398. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  399. //给所有的参数赋值
  400. IDataParameter[] Params = null;
  401. if (ParameterNames != null)
  402. {
  403. if (ParameterNames.GetLength(0) != DbTypes.GetLength(0) && ParameterNames.GetLength(0) != Directions.GetLength(0))
  404. {
  405. throw new Exception("传入参数数据个数不一致!");
  406. }
  407. Params = new IDataParameter[ParameterNames.GetLength(0)];
  408. for (int i = 0; i < ParameterNames.Length; i++)
  409. {
  410. IDbDataParameter parameter = dataProvider.CreateDataParameter();
  411. parameter.ParameterName = ParameterNames[i];
  412. if (conn is System.Data.OracleClient.OracleConnection)
  413. {
  414. try
  415. {
  416. ((System.Data.OracleClient.OracleParameter)parameter).OracleType = (System.Data.OracleClient.OracleType)DbTypes[i];
  417. }
  418. catch
  419. {
  420. parameter.DbType = DbTypes[i];
  421. }
  422. }
  423. else
  424. {
  425. parameter.DbType = DbTypes[i];
  426. }
  427. if (parameter.Direction != System.Data.ParameterDirection.Input)
  428. parameter.Size = 200;
  429. parameter.Direction = Directions[i];
  430. Params[i] = parameter;
  431. }
  432. }
  433. return Params;
  434. }
  435. private DataSet ExecuteQueryFunc(IDbConnection conn, IDbTransaction trans, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, ref ArrayList OutputValues)
  436. {
  437. //////////////////////////////////////////////////////////////////////////测试用//////////////////////////////////////////////////////////////////////////
  438. ExecuteQueryToFile(conn, trans, Sql, cmdType, Params, Values, ref OutputValues);
  439. ////////////////////////////////////////////////////////////////////////////////////
  440. DataSet ds = null;
  441. ds = new DataSet();
  442. if (conn == null)
  443. {
  444. cwl_sql.WriteLog(string.Format("[执行失败:获取数据库连接失败!]\n{0}", Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  445. return SetSerializationType(ds);
  446. }
  447. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  448. IDbCommand command = conn.CreateCommand();
  449. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  450. ((IDbDataAdapter)adapter).SelectCommand = command;
  451. command.CommandText = Sql;
  452. command.CommandType = cmdType;
  453. //设置事务
  454. if (trans != null)
  455. {
  456. command.Transaction = trans;
  457. }
  458. //给所有的参数赋值
  459. if (Params != null && Values != null)
  460. {
  461. for (int i = 0; i < Params.Length; i++)
  462. {
  463. command.Parameters.Add(Params[i]);
  464. ((IDbDataParameter)command.Parameters[i]).Value = Values[i];
  465. }
  466. }
  467. adapter.Fill(ds);
  468. //返回输出参数值
  469. if (OutputValues != null)
  470. {
  471. for (int k = 0; k < command.Parameters.Count; k++)
  472. {
  473. if (((IDbDataParameter)command.Parameters[k]).Direction != ParameterDirection.Input)
  474. {
  475. OutputValues.Add(((IDbDataParameter)command.Parameters[k]).Value);
  476. }
  477. }
  478. }
  479. cwl_sql.WriteLog(adapter.SelectCommand.CommandText, LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  480. return ds;
  481. }
  482. private void ExecuteQueryToFile(IDbConnection conn, IDbTransaction trans, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, ref ArrayList OutputValues)
  483. {
  484. //////////////////////////////////////////////////////////////////////////测试用//////////////////////////////////////////////////////////////////////////
  485. if (!Sql.Contains("mb_orderneedack")) return;
  486. ////////////////////////////////////////////////////////////////////////////////////
  487. DataSet ds = null;
  488. ds = new DataSet();
  489. DataProvider.IDataProvider dataProvider = null;
  490. IDbCommand command = null;
  491. IDataReader reader = null;
  492. FileStream filestream = null;
  493. BinaryWriter bw = null;
  494. try
  495. {
  496. if (conn == null)
  497. {
  498. cwl_sql.WriteLog(string.Format("[执行失败:获取数据库连接失败!]\n{0}", Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  499. return;
  500. }
  501. dataProvider = GetDataProvider(conn.GetType());
  502. command = conn.CreateCommand();
  503. command.CommandText = Sql;
  504. command.CommandType = cmdType;
  505. //设置事务
  506. if (trans != null)
  507. {
  508. command.Transaction = trans;
  509. }
  510. //给所有的参数赋值
  511. if (Params != null && Values != null)
  512. {
  513. for (int i = 0; i < Params.Length; i++)
  514. {
  515. command.Parameters.Add(Params[i]);
  516. ((IDbDataParameter)command.Parameters[i]).Value = Values[i];
  517. }
  518. }
  519. reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
  520. string tmp_file_path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "~senddata");
  521. if (!Directory.Exists(tmp_file_path))
  522. {
  523. Directory.CreateDirectory(tmp_file_path);
  524. }
  525. filestream = new FileStream(Path.Combine(tmp_file_path, DateTime.Now.Ticks.ToString() + ".tmp"), FileMode.CreateNew, FileAccess.ReadWrite);
  526. byte[] buffer = null;
  527. MemoryStream ms = new MemoryStream();
  528. reader.GetSchemaTable().WriteXmlSchema(ms, false);
  529. ms.Flush();
  530. buffer = ms.ToArray();
  531. ms.Close();
  532. bw = new BinaryWriter(filestream);
  533. bw.Write(buffer.GetLength(0));
  534. bw.Write(buffer);
  535. ArrayList Obj = new ArrayList();
  536. bool notFinished = false;
  537. object[] datas = new object[reader.FieldCount];
  538. do
  539. {
  540. notFinished = reader.Read();
  541. if (notFinished)
  542. {
  543. reader.GetValues(datas);
  544. Obj.Add((object)(datas));
  545. }
  546. if (Obj.Count == 1000 || !notFinished)
  547. {
  548. byte[] data_byte = Utility.SerializeAndCompressObject(Obj);
  549. bw.Write(data_byte.GetLength(0));
  550. bw.Write(data_byte);
  551. bw.Flush();
  552. Obj.Clear();
  553. }
  554. } while (notFinished);
  555. //返回输出参数值
  556. if (OutputValues != null)
  557. {
  558. for (int k = 0; k < command.Parameters.Count; k++)
  559. {
  560. if (((IDbDataParameter)command.Parameters[k]).Direction != ParameterDirection.Input)
  561. {
  562. OutputValues.Add(((IDbDataParameter)command.Parameters[k]).Value);
  563. }
  564. }
  565. }
  566. cwl_sql.WriteLog(command.CommandText, LogInfoLevel.Message, "ExecuteQuery", "ExecuteQuery");
  567. }
  568. catch (Exception ex)
  569. {
  570. throw ex;
  571. }
  572. finally
  573. {
  574. if (bw != null) bw.Close();
  575. if (filestream != null) filestream.Close();
  576. }
  577. return;
  578. }
  579. //不通过DBServer时使用
  580. //事务处理
  581. public int ExecuteNonQuery_NoDBSever(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, IDataParameter[] Params, out string err)
  582. {
  583. err = "";
  584. int lines = -1;//受影响的行数
  585. //获取数据库连接...
  586. IDbConnection conn = null;
  587. IDbTransaction trans = null;
  588. //如果是事务
  589. if (_transList.Contains(guid))
  590. {
  591. //Console.WriteLine("事务:执行数据库操作{0}...\n", Sql);
  592. TransInfo info = (TransInfo)_transList[guid];
  593. conn = info.dbConnection;
  594. trans = info.dbTransaction;
  595. //如果事务已经失效,则返回
  596. if (trans.Connection == null)
  597. {
  598. err = "事务已经失效!";
  599. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  600. return lines;
  601. }
  602. }
  603. else
  604. {
  605. err = "未找到请求的事务!";
  606. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  607. return lines;
  608. }
  609. if (conn == null)
  610. {
  611. err = "获取数据库连接失败!";
  612. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  613. return lines;
  614. }
  615. try
  616. {
  617. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  618. IDbCommand command = conn.CreateCommand();
  619. command.CommandText = Sql;
  620. command.CommandType = cmdType;
  621. command.Transaction = trans;
  622. //给所有的参数赋值
  623. if (Params != null)
  624. {
  625. for (int i = 0; i < Params.Length; i++)
  626. {
  627. command.Parameters.Add(Params[i]);
  628. }
  629. }
  630. lines = command.ExecuteNonQuery();
  631. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  632. }
  633. catch (Exception ex)
  634. {
  635. trans.Rollback();
  636. err = ex.Message;
  637. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  638. }
  639. return lines;
  640. }
  641. //非事务处理
  642. public int ExecuteNonQuery_NoDBSever(string dbName, string priority, string Sql, CommandType cmdType, IDataParameter[] Params, out string err)
  643. {
  644. err = "";
  645. int lines = -1;//受影响的行数
  646. //获取数据库连接...
  647. IDbConnection conn = null;
  648. //获取数据库连接
  649. conn = GetDbConnection(dbName, priority, Sql);
  650. if (conn == null)
  651. {
  652. err = "获取数据库连接失败!";
  653. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  654. return lines;
  655. }
  656. try
  657. {
  658. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  659. IDbCommand command = conn.CreateCommand();
  660. command.CommandText = Sql;
  661. command.CommandType = cmdType;
  662. //给所有的参数赋值
  663. if (Params != null)
  664. {
  665. for (int i = 0; i < Params.Length; i++)
  666. {
  667. command.Parameters.Add(Params[i]);
  668. }
  669. }
  670. lines = command.ExecuteNonQuery();
  671. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  672. }
  673. catch (Exception ex)
  674. {
  675. err = ex.Message;
  676. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  677. }
  678. finally
  679. {
  680. ReleaseDbConnection(dbName, priority, conn, Sql);
  681. }
  682. return lines;
  683. }
  684. //执行带参数的SQL语句,返回受影响的行数
  685. //事务处理
  686. public int ExecuteNonQuery(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, out string err)
  687. {
  688. err = "";
  689. int lines = -1;//受影响的行数
  690. //获取数据库连接...
  691. IDbConnection conn = null;
  692. IDbTransaction trans = null;
  693. //如果是事务
  694. if (_transList.Contains(guid))
  695. {
  696. //Console.WriteLine("事务:执行数据库操作{0}...\n", Sql);
  697. TransInfo info = (TransInfo)_transList[guid];
  698. conn = info.dbConnection;
  699. trans = info.dbTransaction;
  700. //如果事务已经失效,则返回
  701. if (trans.Connection == null)
  702. {
  703. err = "事务已经失效!";
  704. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  705. return lines;
  706. }
  707. }
  708. else
  709. {
  710. err = "未找到请求的事务!";
  711. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  712. return lines;
  713. }
  714. if (conn == null)
  715. {
  716. err = "获取数据库连接失败!";
  717. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  718. return lines;
  719. }
  720. try
  721. {
  722. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  723. IDbCommand command = conn.CreateCommand();
  724. command.CommandText = Sql;
  725. command.CommandType = cmdType;
  726. command.Transaction = trans;
  727. //给所有的参数赋值
  728. if (Params != null && Values != null)
  729. {
  730. for (int i = 0; i < Params.Length; i++)
  731. {
  732. command.Parameters.Add(Params[i]);
  733. ((IDbDataParameter)command.Parameters[i]).Value = Values[i];
  734. }
  735. }
  736. lines = command.ExecuteNonQuery();
  737. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  738. }
  739. catch (Exception ex)
  740. {
  741. err = ex.Message;
  742. trans.Rollback();
  743. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteQuery", "ExecuteNonQuery_NoDBSever");
  744. }
  745. return lines;
  746. }
  747. //非事务处理
  748. public int ExecuteNonQuery(string dbName, string priority, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, out string err)
  749. {
  750. err = "";
  751. int lines = -1;//受影响的行数
  752. //获取数据库连接...
  753. IDbConnection conn = null;
  754. //获取数据库连接
  755. conn = GetDbConnection(dbName, priority, Sql);
  756. if (conn == null)
  757. {
  758. err = "获取数据库连接失败!";
  759. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  760. return lines;
  761. }
  762. try
  763. {
  764. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  765. IDbCommand command = conn.CreateCommand();
  766. command.CommandText = Sql;
  767. command.CommandType = cmdType;
  768. //给所有的参数赋值
  769. if (Params != null && Values != null)
  770. {
  771. for (int i = 0; i < Params.Length; i++)
  772. {
  773. command.Parameters.Add(Params[i]);
  774. ((IDbDataParameter)command.Parameters[i]).Value = Values[i];
  775. }
  776. }
  777. lines = command.ExecuteNonQuery();
  778. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  779. }
  780. catch (Exception ex)
  781. {
  782. err = ex.Message;
  783. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  784. }
  785. finally
  786. {
  787. //释放连接
  788. ReleaseDbConnection(dbName, priority, conn, Sql);
  789. }
  790. return lines;
  791. }
  792. //执行带参数的SQL语句,返回受影响的行数
  793. // 事务操作
  794. public int ExecuteNonQuery(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions, bool[] IsNullables, string[] SourceColumns, DataRowVersion[] SourceVersions, object[] Values, ref ArrayList OutputValues, out string err)
  795. {
  796. err = "";
  797. int lines = -1;//受影响的行数
  798. //获取数据库连接...
  799. IDbConnection conn = null;
  800. IDbTransaction trans = null;
  801. //如果是事务
  802. if (_transList.Contains(guid))
  803. {
  804. TransInfo info = (TransInfo)_transList[guid];
  805. conn = info.dbConnection;
  806. trans = info.dbTransaction;
  807. //如果事务已经失效,则返回
  808. if (trans.Connection == null)
  809. {
  810. err = "事务已经失效!";
  811. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  812. return lines;
  813. }
  814. }
  815. else
  816. {
  817. err = "未找到请求的事务!";
  818. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  819. return lines;
  820. }
  821. if (conn == null)
  822. {
  823. err = "获取数据库连接失败!";
  824. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  825. return lines;
  826. }
  827. showsql(Sql);
  828. try
  829. {
  830. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  831. IDbCommand command = conn.CreateCommand();
  832. command.CommandText = Sql;
  833. command.CommandType = cmdType;
  834. //设置事务
  835. command.Transaction = trans;
  836. if (ParameterNames != null)
  837. {
  838. for (int i = 0; i < ParameterNames.Length; i++)
  839. {
  840. IDbDataParameter parameter = dataProvider.CreateDataParameter();
  841. parameter.ParameterName = ParameterNames[i];
  842. parameter.Value = Values[i];
  843. parameter.Direction = Directions[i];
  844. if (conn is System.Data.OracleClient.OracleConnection)
  845. {
  846. try
  847. {
  848. ((System.Data.OracleClient.OracleParameter)parameter).OracleType = (System.Data.OracleClient.OracleType)DbTypes[i];
  849. }
  850. catch
  851. {
  852. parameter.DbType = DbTypes[i];
  853. }
  854. }
  855. else
  856. {
  857. parameter.DbType = DbTypes[i];
  858. }
  859. if (parameter.Direction != System.Data.ParameterDirection.Input)
  860. parameter.Size = 200;
  861. parameter.Direction = Directions[i];
  862. command.Parameters.Add(parameter);
  863. }
  864. }
  865. lines = command.ExecuteNonQuery();
  866. //返回输出参数值
  867. if (OutputValues != null)
  868. {
  869. for (int k = 0; k < command.Parameters.Count; k++)
  870. {
  871. if (((IDbDataParameter)command.Parameters[k]).Direction != ParameterDirection.Input)
  872. {
  873. OutputValues.Add(((IDbDataParameter)command.Parameters[k]).Value);
  874. }
  875. }
  876. }
  877. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  878. }
  879. catch (System.Exception ex)
  880. {
  881. err = ex.Message;
  882. trans.Rollback();
  883. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  884. }
  885. return lines;
  886. }
  887. //非事务处理
  888. public int ExecuteNonQuery(string dbName, string priority, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions, bool[] IsNullables, string[] SourceColumns, DataRowVersion[] SourceVersions, object[] Values, ref ArrayList OutputValues, out string err)
  889. {
  890. err = "";
  891. int lines = -1;//受影响的行数
  892. //获取数据库连接...
  893. IDbConnection conn = null;
  894. //获取数据库连接
  895. conn = GetDbConnection(dbName, priority, Sql);
  896. if (conn == null)
  897. {
  898. err = "获取数据库连接失败!";
  899. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  900. return lines;
  901. }
  902. try
  903. {
  904. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  905. IDbCommand command = conn.CreateCommand();
  906. command.CommandText = Sql;
  907. command.CommandType = cmdType;
  908. //给所有的参数赋值
  909. if (ParameterNames != null)
  910. {
  911. for (int i = 0; i < ParameterNames.Length; i++)
  912. {
  913. IDbDataParameter parameter = dataProvider.CreateDataParameter();
  914. parameter.ParameterName = ParameterNames[i];
  915. parameter.Value = Values[i];
  916. parameter.Direction = Directions[i];
  917. if (conn is System.Data.OracleClient.OracleConnection)
  918. {
  919. try
  920. {
  921. ((System.Data.OracleClient.OracleParameter)parameter).OracleType = (System.Data.OracleClient.OracleType)DbTypes[i];
  922. }
  923. catch
  924. {
  925. parameter.DbType = DbTypes[i];
  926. }
  927. }
  928. else
  929. {
  930. parameter.DbType = DbTypes[i];
  931. }
  932. if (parameter.Direction != System.Data.ParameterDirection.Input)
  933. parameter.Size = 200;
  934. parameter.Direction = Directions[i];
  935. command.Parameters.Add(parameter);
  936. }
  937. }
  938. lines = command.ExecuteNonQuery();
  939. //返回输出参数值
  940. if (OutputValues != null)
  941. {
  942. for (int k = 0; k < command.Parameters.Count; k++)
  943. {
  944. if (((IDbDataParameter)command.Parameters[k]).Direction != ParameterDirection.Input)
  945. {
  946. OutputValues.Add(((IDbDataParameter)command.Parameters[k]).Value);
  947. }
  948. }
  949. }
  950. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  951. }
  952. catch (Exception ex)
  953. {
  954. err = ex.Message;
  955. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  956. }
  957. finally
  958. {
  959. //释放连接
  960. ReleaseDbConnection(dbName, priority, conn, Sql);
  961. }
  962. return lines;
  963. }
  964. //事务处理
  965. public int ExecuteNonQuery(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions, bool[] IsNullables, string[] SourceColumns, DataRowVersion[] SourceVersions, int[] Sizes, object[] Values, ref ArrayList OutputValues, out string err)
  966. {
  967. err = "";
  968. int lines = -1;//受影响的行数
  969. //获取数据库连接...
  970. IDbConnection conn = null;
  971. IDbTransaction trans = null;
  972. //如果是事务
  973. if (_transList.Contains(guid))
  974. {
  975. //Console.WriteLine("事务:执行数据库操作{0}...\n", Sql);
  976. TransInfo info = (TransInfo)_transList[guid];
  977. conn = info.dbConnection;
  978. trans = info.dbTransaction;
  979. //如果事务已经失效,则返回
  980. if (trans.Connection == null)
  981. {
  982. err = "事务已经失效!";
  983. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  984. return lines;
  985. }
  986. }
  987. else
  988. {
  989. err = "未找到请求的事务!";
  990. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  991. return lines;
  992. }
  993. if (conn == null)
  994. {
  995. err = "获取数据库连接失败!";
  996. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  997. return lines;
  998. }
  999. try
  1000. {
  1001. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  1002. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  1003. IDbCommand command = conn.CreateCommand();
  1004. command.CommandText = Sql;
  1005. command.CommandType = cmdType;
  1006. command.Transaction = trans;
  1007. //给所有的参数赋值
  1008. if (ParameterNames != null && DbTypes != null && Values != null)
  1009. {
  1010. for (int i = 0; i < ParameterNames.Length; i++)
  1011. {
  1012. IDbDataParameter parameter = dataProvider.CreateDataParameter();
  1013. parameter.ParameterName = ParameterNames[i];
  1014. if (conn is System.Data.OracleClient.OracleConnection)
  1015. {
  1016. try
  1017. {
  1018. ((System.Data.OracleClient.OracleParameter)parameter).OracleType = (System.Data.OracleClient.OracleType)DbTypes[i];
  1019. }
  1020. catch
  1021. {
  1022. parameter.DbType = DbTypes[i];
  1023. }
  1024. }
  1025. else
  1026. {
  1027. parameter.DbType = DbTypes[i];
  1028. }
  1029. parameter.Direction = Directions[i];
  1030. if (parameter.Direction != System.Data.ParameterDirection.Input)
  1031. parameter.Size = 200;
  1032. parameter.Direction = Directions[i];
  1033. parameter.Value = Values[i];
  1034. command.Parameters.Add(parameter);
  1035. }
  1036. }
  1037. lines = command.ExecuteNonQuery();
  1038. //返回输出参数值
  1039. if (OutputValues != null)
  1040. {
  1041. for (int k = 0; k < command.Parameters.Count; k++)
  1042. {
  1043. if (((IDbDataParameter)command.Parameters[k]).Direction != ParameterDirection.Input)
  1044. {
  1045. OutputValues.Add(((IDbDataParameter)command.Parameters[k]).Value);
  1046. }
  1047. }
  1048. }
  1049. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  1050. }
  1051. catch (Exception ex)
  1052. {
  1053. err = ex.Message;
  1054. trans.Rollback();
  1055. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  1056. }
  1057. return lines;
  1058. }
  1059. //非事务处理
  1060. public int ExecuteNonQuery(string dbName, string priority, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, ParameterDirection[] Directions, bool[] IsNullables, string[] SourceColumns, DataRowVersion[] SourceVersions, int[] Sizes, object[] Values, ref ArrayList OutputValues, out string err)
  1061. {
  1062. err = "";
  1063. int lines = -1;//受影响的行数
  1064. //获取数据库连接...
  1065. IDbConnection conn = null;
  1066. //获取数据库连接
  1067. conn = GetDbConnection(dbName, priority, Sql);
  1068. if (conn == null)
  1069. {
  1070. err = "获取数据库连接失败!";
  1071. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  1072. return lines;
  1073. }
  1074. showsql(Sql);
  1075. try
  1076. {
  1077. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  1078. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  1079. IDbCommand command = conn.CreateCommand();
  1080. command.CommandText = Sql;
  1081. command.CommandType = cmdType;
  1082. //给所有的参数赋值
  1083. if (ParameterNames != null && DbTypes != null && Values != null)
  1084. {
  1085. for (int i = 0; i < ParameterNames.Length; i++)
  1086. {
  1087. IDbDataParameter parameter = dataProvider.CreateDataParameter();
  1088. parameter.ParameterName = ParameterNames[i];
  1089. if (conn is System.Data.OracleClient.OracleConnection)
  1090. {
  1091. try
  1092. {
  1093. ((System.Data.OracleClient.OracleParameter)parameter).OracleType = (System.Data.OracleClient.OracleType)DbTypes[i];
  1094. }
  1095. catch
  1096. {
  1097. parameter.DbType = DbTypes[i];
  1098. }
  1099. }
  1100. else
  1101. {
  1102. parameter.DbType = DbTypes[i];
  1103. }
  1104. parameter.Direction = Directions[i];
  1105. parameter.Size = Sizes[i];
  1106. parameter.Value = Values[i];
  1107. command.Parameters.Add(parameter);
  1108. }
  1109. }
  1110. lines = command.ExecuteNonQuery();
  1111. //返回输出参数值
  1112. if (OutputValues != null)
  1113. {
  1114. for (int k = 0; k < command.Parameters.Count; k++)
  1115. {
  1116. if (((IDbDataParameter)command.Parameters[k]).Direction != ParameterDirection.Input)
  1117. {
  1118. OutputValues.Add(((IDbDataParameter)command.Parameters[k]).Value);
  1119. }
  1120. }
  1121. }
  1122. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  1123. }
  1124. catch (Exception ex)
  1125. {
  1126. err = ex.Message;
  1127. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "ExecuteNonQuery", "ExecuteNonQuery");
  1128. }
  1129. finally
  1130. {
  1131. ReleaseDbConnection(dbName, priority, conn, Sql);
  1132. }
  1133. return lines;
  1134. }
  1135. public bool UpdateTable(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, DataTable dt, out string err)
  1136. {
  1137. err = "";
  1138. bool result = true;
  1139. //获取数据库连接...
  1140. IDbConnection conn = null;
  1141. IDbTransaction trans = null;
  1142. //如果是事务
  1143. if (_transList.Contains(guid))
  1144. {
  1145. //Console.WriteLine("事务:更新DataSet<{0}>...\n", Sql);
  1146. TransInfo info = (TransInfo)_transList[guid];
  1147. conn = info.dbConnection;
  1148. trans = info.dbTransaction;
  1149. //如果事务已经失效,则返回
  1150. if (trans.Connection == null)
  1151. {
  1152. err = "事务已经失效!";
  1153. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1154. return false;
  1155. }
  1156. }
  1157. else
  1158. {
  1159. err = "未找到请求的事务!";
  1160. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1161. return false;
  1162. }
  1163. if (conn == null)
  1164. {
  1165. err = "获取数据库连接失败!";
  1166. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1167. return false;
  1168. }
  1169. try
  1170. {
  1171. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  1172. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  1173. IDbCommand command = conn.CreateCommand();
  1174. command.CommandText = Sql;
  1175. command.CommandType = cmdType;
  1176. command.Transaction = trans;
  1177. ((IDbDataAdapter)adapter).SelectCommand = command;
  1178. //给所有的参数赋值
  1179. if (Params != null && Values != null)
  1180. {
  1181. for (int i = 0; i < Params.Length; i++)
  1182. {
  1183. command.Parameters.Add(Params[i]);
  1184. }
  1185. }
  1186. //自动生成SqlCommand命令
  1187. object CB = dataProvider.CreateCommandBuilder(adapter);
  1188. //提交数据更改
  1189. adapter.Update(dt);
  1190. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  1191. }
  1192. catch (Exception ex)
  1193. {
  1194. err = ex.Message;
  1195. trans.Rollback();
  1196. result = false;
  1197. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1198. }
  1199. return result;
  1200. }
  1201. //非事务处理
  1202. public bool UpdateTable(string dbName, string priority, string Sql, CommandType cmdType, IDataParameter[] Params, object[] Values, DataTable dt, out string err)
  1203. {
  1204. err = "";
  1205. bool result = false;
  1206. //获取数据库连接...
  1207. IDbConnection conn = null;
  1208. //获取数据库连接
  1209. conn = GetDbConnection(dbName, priority, Sql);
  1210. if (conn == null)
  1211. {
  1212. err = "获取数据库连接失败!";
  1213. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1214. return false;
  1215. }
  1216. try
  1217. {
  1218. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  1219. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  1220. IDbCommand command = conn.CreateCommand();
  1221. command.CommandText = Sql;
  1222. command.CommandType = cmdType;
  1223. ((IDbDataAdapter)adapter).SelectCommand = command;
  1224. //给所有的参数赋值
  1225. if (Params != null && Values != null)
  1226. {
  1227. for (int i = 0; i < Params.Length; i++)
  1228. {
  1229. command.Parameters.Add(Params[i]);
  1230. ((IDbDataParameter)command.Parameters[i]).Value = Values[i];
  1231. }
  1232. }
  1233. //自动生成SqlCommand命令
  1234. object CB = dataProvider.CreateCommandBuilder(adapter);
  1235. //提交数据更改
  1236. adapter.Update(dt);
  1237. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  1238. }
  1239. catch (Exception ex)
  1240. {
  1241. err = ex.Message;
  1242. result = false;
  1243. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1244. }
  1245. finally
  1246. {
  1247. ReleaseDbConnection(dbName, priority, conn, Sql);
  1248. }
  1249. return result;
  1250. }
  1251. //事务处理
  1252. public bool UpdateTable(string dbName, string priority, Guid guid, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, object[] Values, DataTable dt, out string err)
  1253. {
  1254. err = "";
  1255. bool result = true;
  1256. //获取数据库连接...
  1257. IDbConnection conn = null;
  1258. IDbTransaction trans = null;
  1259. //如果是事务
  1260. if (_transList.Contains(guid))
  1261. {
  1262. //Console.WriteLine("事务:更新DataSet<{0}>...\n", Sql);
  1263. TransInfo info = (TransInfo)_transList[guid];
  1264. conn = info.dbConnection;
  1265. trans = info.dbTransaction;
  1266. //如果事务已经失效,则返回
  1267. if (trans.Connection == null)
  1268. {
  1269. err = "事务已经失效!";
  1270. cwl.WriteLog(err, LogInfoLevel.Error, "UpdateTable", "事务1");
  1271. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1272. return false;
  1273. }
  1274. }
  1275. else
  1276. {
  1277. err = "未找到请求的事务!";
  1278. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1279. return false;
  1280. }
  1281. if (conn == null)
  1282. {
  1283. err = "获取数据库连接失败!";
  1284. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1285. return false;
  1286. }
  1287. try
  1288. {
  1289. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  1290. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  1291. IDbCommand command = conn.CreateCommand();
  1292. command.CommandText = Sql;
  1293. command.CommandType = cmdType;
  1294. command.Transaction = trans;
  1295. //给所有的参数赋值
  1296. if (ParameterNames != null && DbTypes != null && Values != null)
  1297. {
  1298. for (int i = 0; i < ParameterNames.Length; i++)
  1299. {
  1300. IDbDataParameter parameter = dataProvider.CreateDataParameter();
  1301. parameter.ParameterName = ParameterNames[i];
  1302. if (conn is System.Data.OracleClient.OracleConnection)
  1303. {
  1304. try
  1305. {
  1306. ((System.Data.OracleClient.OracleParameter)parameter).OracleType = (System.Data.OracleClient.OracleType)DbTypes[i];
  1307. }
  1308. catch
  1309. {
  1310. parameter.DbType = DbTypes[i];
  1311. }
  1312. }
  1313. else
  1314. {
  1315. parameter.DbType = DbTypes[i];
  1316. }
  1317. parameter.Value = Values[i];
  1318. command.Parameters.Add(parameter);
  1319. }
  1320. }
  1321. ((IDbDataAdapter)adapter).SelectCommand = command;
  1322. //自动生成SqlCommand命令
  1323. object CB = dataProvider.CreateCommandBuilder(adapter);
  1324. //提交数据更改
  1325. adapter.Update(dt);
  1326. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  1327. }
  1328. catch (Exception ex)
  1329. {
  1330. err = ex.Message;
  1331. trans.Rollback();
  1332. result = false;
  1333. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1334. }
  1335. return result;
  1336. }
  1337. //非事务处理
  1338. public bool UpdateTable(string dbName, string priority, string Sql, CommandType cmdType, string[] ParameterNames, DbType[] DbTypes, object[] Values, DataTable dt, out string err)
  1339. {
  1340. err = "";
  1341. bool result = true;
  1342. //获取数据库连接...
  1343. IDbConnection conn = null;
  1344. //获取数据库连接
  1345. conn = GetDbConnection(dbName, priority, Sql);
  1346. if (conn == null)
  1347. {
  1348. err = "获取数据库连接失败!";
  1349. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1350. return false;
  1351. }
  1352. try
  1353. {
  1354. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  1355. DbDataAdapter adapter = dataProvider.CreateDataAdapterObject();
  1356. IDbCommand command = conn.CreateCommand();
  1357. command.CommandText = Sql;
  1358. command.CommandType = cmdType;
  1359. //给所有的参数赋值
  1360. if (ParameterNames != null && DbTypes != null && Values != null)
  1361. {
  1362. for (int i = 0; i < ParameterNames.Length; i++)
  1363. {
  1364. IDbDataParameter parameter = dataProvider.CreateDataParameter();
  1365. parameter.ParameterName = ParameterNames[i];
  1366. if (conn is System.Data.OracleClient.OracleConnection)
  1367. {
  1368. try
  1369. {
  1370. ((System.Data.OracleClient.OracleParameter)parameter).OracleType = (System.Data.OracleClient.OracleType)DbTypes[i];
  1371. }
  1372. catch
  1373. {
  1374. parameter.DbType = DbTypes[i];
  1375. }
  1376. }
  1377. else
  1378. {
  1379. parameter.DbType = DbTypes[i];
  1380. }
  1381. parameter.Value = Values[i];
  1382. command.Parameters.Add(parameter);
  1383. }
  1384. }
  1385. ((IDbDataAdapter)adapter).SelectCommand = command;
  1386. //自动生成SqlCommand命令
  1387. object CB = dataProvider.CreateCommandBuilder(adapter);
  1388. //提交数据更改
  1389. adapter.Update(dt);
  1390. cwl_sql.WriteLog(PraseProducePara(command), LogInfoLevel.Message, command.CommandType.ToString(), command.CommandText);
  1391. }
  1392. catch (Exception ex)
  1393. {
  1394. err = ex.Message;
  1395. result = false;
  1396. cwl_sql.WriteLog(string.Format("[执行失败:{0}]\n{1}", err, Sql), LogInfoLevel.Message, "UpdateTable", "UpdateTable");
  1397. }
  1398. finally
  1399. {
  1400. //释放连接
  1401. ReleaseDbConnection(dbName, priority, conn, Sql);
  1402. }
  1403. return result;
  1404. }
  1405. #endregion
  1406. #region"基础操作"
  1407. public IDbCommand GetCommand(string dbName, string priority, Guid guid, out string err)
  1408. {
  1409. err = "";
  1410. //获取数据库连接...
  1411. IDbConnection conn = null;
  1412. IDbTransaction trans = null;
  1413. //如果是事务
  1414. if (_transList.Contains(guid))
  1415. {
  1416. //Console.WriteLine("事务:更新DataSet<{0}>...\n", Sql);
  1417. TransInfo info = (TransInfo)_transList[guid];
  1418. conn = info.dbConnection;
  1419. trans = info.dbTransaction;
  1420. //如果事务已经失效,则返回
  1421. if (trans.Connection == null)
  1422. {
  1423. err = "事务已经失效";
  1424. return null;
  1425. }
  1426. }
  1427. else
  1428. {
  1429. //Console.WriteLine("更新DataSet<{0}>...\n", Sql);
  1430. //获取数据库连接
  1431. conn = GetDbConnection(dbName, priority, "GetCommand");
  1432. }
  1433. if (conn == null)
  1434. {
  1435. err = "获取数据库连接失败!";
  1436. return null;
  1437. }
  1438. IDbCommand command = conn.CreateCommand();
  1439. return command;
  1440. }
  1441. public IDbTransaction GetTransaction(string dbName, string priority, Guid guid, out string err)
  1442. {
  1443. err = "";
  1444. IDbConnection conn = null;
  1445. IDbTransaction trans = null;
  1446. //如果是事务
  1447. if (_transList.Contains(guid))
  1448. {
  1449. //Console.WriteLine("事务:更新DataSet<{0}>...\n", Sql);
  1450. TransInfo info = (TransInfo)_transList[guid];
  1451. trans = info.dbTransaction;
  1452. conn = info.dbConnection;
  1453. //如果事务已经失效,则返回
  1454. if (trans.Connection == null)
  1455. {
  1456. err = "事务已经失效";
  1457. return null;
  1458. }
  1459. }
  1460. else
  1461. {
  1462. err = "没有事务!";
  1463. return null;
  1464. }
  1465. if (conn == null)
  1466. {
  1467. err = "获取数据库连接失败!";
  1468. return null;
  1469. }
  1470. return trans;
  1471. }
  1472. /// <summary>
  1473. /// 获取连接提供者
  1474. /// </summary>
  1475. /// <param name="configurationString"></param>
  1476. /// <returns></returns>
  1477. private static DataProvider.IDataProvider GetDataProvider(string dbType)
  1478. {
  1479. DataProvider.IDataProvider dataProvider =
  1480. (DataProvider.IDataProvider)_dataProviderNameList[dbType.ToUpper()];
  1481. return dataProvider;
  1482. }
  1483. public DataProvider.IDataProvider GetDataProvider(string dbName, out string err)
  1484. {
  1485. err = "";
  1486. return GetDataProvider(this.GetDbType(dbName, out err));
  1487. }
  1488. public DataProvider.IDataProvider GetDataProvider(Guid guid, out string err)
  1489. {
  1490. err = "";
  1491. IDbConnection conn = null;
  1492. //如果是事务
  1493. if (_transList.Contains(guid))
  1494. {
  1495. //Console.WriteLine("事务:更新DataSet<{0}>...\n", Sql);
  1496. TransInfo info = (TransInfo)_transList[guid];
  1497. conn = info.dbConnection;
  1498. }
  1499. if (conn == null)
  1500. {
  1501. err = "获取数据库连接失败!";
  1502. return null;
  1503. }
  1504. return GetDataProvider(conn.GetType());
  1505. }
  1506. private static DataProvider.IDataProvider GetDataProvider(System.Type dbType)
  1507. {
  1508. DataProvider.IDataProvider dataProvider =
  1509. (DataProvider.IDataProvider)_dataProviderTypeList[dbType];
  1510. return dataProvider;
  1511. }
  1512. public System.Guid BeginTransaction(string dbName, string priority, long dbManagerID, double minutes, out string err)
  1513. {
  1514. return BeginTransaction("", dbName, priority, dbManagerID, minutes, out err);
  1515. }
  1516. /// <summary>
  1517. /// 开始处理事务,同时指定该事务最长处理时间,单位为分钟,返回结果表示是否成功
  1518. /// 不支持嵌套事务
  1519. /// </summary>
  1520. /// <param name="dbName"></param>
  1521. /// <param name="priority"></param>
  1522. /// <param name="dbManagerID"></param>
  1523. /// <param name="minutes"></param>
  1524. /// <param name="err"></param>
  1525. /// <returns></returns>
  1526. public System.Guid BeginTransaction(string methodName, string dbName, string priority, long dbManagerID, double minutes, out string err)
  1527. {
  1528. lock (_transList)
  1529. {
  1530. err = "";
  1531. Guid guid = Guid.NewGuid();
  1532. //获取数据库连接
  1533. IDbConnection conn = GetDbConnection(dbName, priority, methodName);
  1534. if (conn == null)
  1535. {
  1536. err = "获取数据库连接失败!";
  1537. return guid;
  1538. }
  1539. //设置事务信息,包括数据库连接、事务、事务开始时间等
  1540. TransInfo info = new TransInfo();
  1541. info.dbConnection = conn;
  1542. info.beginTime = DateTime.Now;
  1543. info.dbManagerID = dbManagerID;
  1544. try
  1545. {
  1546. info.dbTransaction = conn.BeginTransaction(); ;
  1547. _transList.Add(guid, info);
  1548. }
  1549. catch (Exception ex)
  1550. {
  1551. err = ex.Message;
  1552. ReleaseDbConnection(dbName, priority, conn, err);
  1553. }
  1554. return guid;
  1555. }
  1556. }
  1557. //提交当前事务,返回结果表示是否成功
  1558. public bool Commit(string dbName, string priority, Guid guid, out string err)
  1559. {
  1560. lock (_transList)
  1561. {
  1562. bool result = true;
  1563. err = "";
  1564. if (!_transList.Contains(guid))
  1565. {
  1566. err = "不存在要提交的事务";
  1567. return false;
  1568. }
  1569. TransInfo info = (TransInfo)_transList[guid];
  1570. IDbConnection conn = info.dbConnection;
  1571. IDbTransaction trans = info.dbTransaction;
  1572. try
  1573. {
  1574. trans.Commit();
  1575. }
  1576. catch (Exception ex)
  1577. {
  1578. err = ex.Message;
  1579. result = false;
  1580. cwl.WriteLog(err, LogInfoLevel.Error, "Rollback", "");
  1581. }
  1582. finally
  1583. {
  1584. //删除事务
  1585. ReleaseDbConnection(dbName, priority, conn, "Commit:" + guid.ToString());
  1586. _transList.Remove(guid);
  1587. }
  1588. return result;
  1589. }
  1590. }
  1591. //回滚当前事务,返回结果表示是否成功
  1592. public bool Rollback(string dbName, string priority, Guid guid, out string err)
  1593. {
  1594. lock (_transList)
  1595. {
  1596. bool result = true;
  1597. err = "";
  1598. if (!_transList.Contains(guid))
  1599. {
  1600. err = "不存在要回滚的事务";
  1601. return false;
  1602. }
  1603. TransInfo info = (TransInfo)_transList[guid];
  1604. IDbConnection conn = info.dbConnection;
  1605. IDbTransaction trans = info.dbTransaction;
  1606. try
  1607. {
  1608. trans.Rollback();
  1609. }
  1610. catch (Exception ex)
  1611. {
  1612. err = ex.Message;
  1613. result = false;
  1614. cwl.WriteLog(err, LogInfoLevel.Error, "Rollback", "");
  1615. }
  1616. finally
  1617. {
  1618. //删除事务
  1619. ReleaseDbConnection(dbName, priority, conn, "Rollback:" + guid.ToString());
  1620. _transList.Remove(guid);
  1621. }
  1622. return result;
  1623. }
  1624. }
  1625. /// <summary>
  1626. /// 从数据库配置文件中读取数据库连接信息
  1627. /// </summary>
  1628. /// <param name="fileName">文件名称</param>
  1629. /// <returns>是否成功</returns>
  1630. private bool ReadDbConnectionInfo(string fileName)
  1631. {
  1632. _dbConfigInfo = new Hashtable();
  1633. string dbName = "";
  1634. string type = "";
  1635. string priority = "";
  1636. string maxNum = "";
  1637. //如果文件存在则读取配置文件
  1638. if (File.Exists(fileName) == true)
  1639. {
  1640. try
  1641. {
  1642. XmlTextReader reader = null;
  1643. try
  1644. {
  1645. //打开数据库配置文件,并忽略所有的空格
  1646. reader = new XmlTextReader(fileName);
  1647. reader.WhitespaceHandling = WhitespaceHandling.None;
  1648. DBConnectionInfo dbConnectionInfo = new DBConnectionInfo();
  1649. dbConnectionInfo.connectionPool = new Hashtable();
  1650. //解释XML文件
  1651. while (reader.Read())
  1652. {
  1653. //bool bFlag = false;
  1654. switch (reader.NodeType)
  1655. {
  1656. case XmlNodeType.Element:
  1657. type = reader.Name;
  1658. break;
  1659. case XmlNodeType.Text:
  1660. if (type.Equals("name"))
  1661. {
  1662. dbName = reader.Value;
  1663. dbConnectionInfo.dbName = dbName;
  1664. }
  1665. else
  1666. {
  1667. if (type.Equals("type"))
  1668. {
  1669. dbConnectionInfo.dbType = reader.Value;
  1670. }
  1671. else
  1672. {
  1673. if (type.Equals("connectionString"))
  1674. {
  1675. dbConnectionInfo.connectionString = reader.Value;
  1676. }
  1677. else
  1678. {
  1679. if (type.Equals("connectionPool"))
  1680. {
  1681. //dbConnectionInfo.connectionPool = new Hashtable();
  1682. }
  1683. else
  1684. {
  1685. if (type.Equals("priority"))
  1686. {
  1687. priority = reader.Value;
  1688. }
  1689. else
  1690. {
  1691. if (type.Equals("maxConnectionNum"))
  1692. {
  1693. maxNum = reader.Value;
  1694. }
  1695. }
  1696. }
  1697. }
  1698. }
  1699. }
  1700. type = "";
  1701. break;
  1702. case XmlNodeType.EndElement:
  1703. if (reader.Name.Equals("connectionPool"))
  1704. {
  1705. dbConnectionInfo.connectionPool.Add(priority, maxNum);
  1706. priority = "";
  1707. maxNum = "";
  1708. }
  1709. else
  1710. {
  1711. if (reader.Name.Equals("database"))
  1712. {
  1713. _dbConfigInfo.Add(dbName, dbConnectionInfo);
  1714. dbName = "";
  1715. dbConnectionInfo = new DBConnectionInfo();
  1716. dbConnectionInfo.connectionPool = new Hashtable();
  1717. }
  1718. }
  1719. break;
  1720. }
  1721. }
  1722. }
  1723. catch
  1724. {
  1725. string errMsg = string.Format("读取数据库定义文件 [{0}] 出错! Last_Item:[{1}]", fileName, dbName);
  1726. cwl.WriteLog(errMsg);
  1727. ShowLog(errMsg);
  1728. }
  1729. finally
  1730. {
  1731. if (reader != null)
  1732. reader.Close();
  1733. }
  1734. }
  1735. catch
  1736. {
  1737. return false;
  1738. }
  1739. }
  1740. else//读取默认设置
  1741. {
  1742. return false;
  1743. }
  1744. return true;
  1745. }
  1746. // 获取数据库连接
  1747. private IDbConnection GetDbConnection(string dbName, string priority, string sqlstr)
  1748. {
  1749. IDbConnection conn = null;
  1750. //直接从数据库连接池中取连接,无连接则直接返回
  1751. Hashtable ht1 = (Hashtable)_connList[dbName];
  1752. if (ht1 == null)
  1753. {
  1754. cwl.WriteLog("获取数据库连接失败!", LogInfoLevel.Message, "ht1:" + dbName, "GetDbConnection");
  1755. return conn;
  1756. }
  1757. try
  1758. {
  1759. Hashtable ht2 = (Hashtable)ht1[priority];
  1760. }
  1761. catch (Exception eeeee) {
  1762. cwl.WriteLog("获取数据库连接失败!", LogInfoLevel.Message, "ht1:" + dbName, eeeee.Message);
  1763. }
  1764. if (ht2 == null)
  1765. {
  1766. cwl.WriteLog("获取数据库连接失败!", LogInfoLevel.Message, "ht2:" + dbName + "/" + priority, "GetDbConnection");
  1767. return conn;
  1768. }
  1769. lock (ht2)
  1770. {
  1771. ArrayList freeList = ht2[0] as ArrayList;
  1772. //排队,最长时间1秒
  1773. //{
  1774. // for (int i = 0; i < 10; i++)
  1775. // {
  1776. // Thread.Sleep(100);
  1777. // if (freeList.Count > 0)
  1778. // {
  1779. // i = 10;
  1780. // }
  1781. // }
  1782. //}
  1783. if (freeList.Count <= 0)
  1784. {
  1785. ArrayList al = ht2[1] as ArrayList;
  1786. if (al == null) al = new ArrayList();
  1787. cwl.WriteLog("数据库忙,请稍后再试!", LogInfoLevel.Message, "<<<>>> " + dbName + " <<<>>> freeList||" + al.Count.ToString(), "GetDbConnection");
  1788. return null;
  1789. }
  1790. conn = (IDbConnection)freeList[0];
  1791. freeList.Remove(conn);
  1792. Hashtable busyList = (Hashtable)ht2[1];
  1793. if (busyList == null)
  1794. {
  1795. busyList = new Hashtable();
  1796. ht2.Add(1, busyList);
  1797. }
  1798. DataProvider.IDataProvider dataProvider = GetDataProvider(conn.GetType());
  1799. try
  1800. {
  1801. if (conn.State != ConnectionState.Open)
  1802. {
  1803. string strConnState = conn.State.ToString();
  1804. conn.Close();
  1805. conn.Dispose();
  1806. conn = null;
  1807. GC.Collect();
  1808. foreach (DictionaryEntry it in _dbConfigInfo)
  1809. {
  1810. DBConnectionInfo info = (DBConnectionInfo)it.Value;
  1811. if (info.dbName == dbName)
  1812. {
  1813. conn = dataProvider.CreateConnectionObject(info.connectionString);
  1814. conn.Open();
  1815. cwl.WriteLog("重连成功!||连接状态:" + strConnState, LogInfoLevel.Message, info.dbName, "GetDbConnection");
  1816. break;
  1817. }
  1818. }
  1819. }
  1820. }
  1821. catch (Exception ex)
  1822. {
  1823. cwl.WriteLog(ex.Message, LogInfoLevel.Error, "", "GetDbConnection");
  1824. return null;
  1825. }
  1826. CurrConnOperateInfo cco = new CurrConnOperateInfo();
  1827. cco.dt = DateTime.Now;
  1828. cco.sqlstr = sqlstr;
  1829. cco.SID = dataProvider.GetSID(ref conn);
  1830. busyList.Add(conn, cco);
  1831. return conn;
  1832. }
  1833. }
  1834. private void ReleaseDbConnection(string dbName, string priority, IDbConnection conn, string SqlText)
  1835. {
  1836. if (conn == null) { return; }
  1837. Hashtable ht1 = (Hashtable)_connList[dbName];
  1838. if (ht1 == null) { return; }
  1839. Hashtable ht2 = (Hashtable)ht1[priority];
  1840. if (ht2 == null) { return; }
  1841. lock (ht2)
  1842. {
  1843. Hashtable busyList = (Hashtable)ht2[1];
  1844. if (busyList != null)
  1845. {
  1846. if (!busyList.Contains(conn))
  1847. {
  1848. // 连接已被检验线程处理,此处不在处理
  1849. //cwl.WriteLog(SqlText, LogInfoLevel.Message, "", "ReleaseDbConnection");
  1850. return;
  1851. }
  1852. busyList.Remove(conn);
  1853. }
  1854. ArrayList freeList = ht2[0] as ArrayList;
  1855. if (freeList == null)
  1856. {
  1857. freeList = new ArrayList();
  1858. ht2.Add(0, freeList);
  1859. }
  1860. freeList.Add(conn);
  1861. }
  1862. }
  1863. /// <summary>
  1864. /// 初始化数据提供接口
  1865. /// </summary>
  1866. /// <param name="dataProvider"></param>
  1867. public static void AddDataProvider(DataProvider.IDataProvider dataProvider)
  1868. {
  1869. _dataProviderNameList[dataProvider.Name.ToUpper()] = dataProvider;
  1870. _dataProviderTypeList[dataProvider.ConnectionType] = dataProvider;
  1871. }
  1872. private void CreateAllConnections()
  1873. {
  1874. //如果连接已经创建,则返回
  1875. if (_connList.Count > 0)
  1876. {
  1877. return;
  1878. }
  1879. int idx = 0;
  1880. foreach (DictionaryEntry it in _dbConfigInfo)
  1881. {
  1882. DBConnectionInfo info = (DBConnectionInfo)it.Value;
  1883. DataProvider.IDataProvider dataProvider = GetDataProvider(info.dbType);
  1884. Hashtable ht1 = new Hashtable();
  1885. idx++;
  1886. ShowLog(string.Format(" [{0}/{1}] {2} {3}", idx, _dbConfigInfo.Count, info.dbName, info.dbType));
  1887. int jdx = 0;
  1888. foreach (DictionaryEntry pool in info.connectionPool)
  1889. {
  1890. jdx++;
  1891. Hashtable ht2 = new Hashtable();
  1892. ArrayList connList = new ArrayList();
  1893. for (int i = 0; i < Convert.ToInt32(pool.Value); i++)
  1894. {
  1895. ShowLog(string.Format(" 连接池[{4}/{5}]: 建立连接[{0}/{1}]: {2} ({3})", i + 1, Convert.ToInt32(pool.Value), info.dbName, info.dbType, jdx, info.connectionPool.Count));
  1896. try
  1897. {
  1898. IDbConnection conn = dataProvider.CreateConnectionObject(info.connectionString);
  1899. conn.Open();
  1900. connList.Add(conn);
  1901. }
  1902. catch
  1903. {
  1904. cwl.WriteLog("创建数据库连接" + info.dbName + " " + pool.Key + " " + i.ToString() + "失败!", LogInfoLevel.Error, info.dbName, "CreateAllConnections");
  1905. break;
  1906. }
  1907. }
  1908. ht2.Add(0, connList);
  1909. ht1.Add(pool.Key, ht2);
  1910. }
  1911. _connList.Add(info.dbName, ht1);
  1912. }
  1913. cwl.WriteLog("启动成功!数据库连接池创建成功!");
  1914. }
  1915. #region 原来代码 maliang 2011-10-19
  1916. /*
  1917. private void FixConnections()
  1918. {
  1919. while (true)
  1920. {
  1921. try
  1922. {
  1923. foreach (DictionaryEntry it in _dbConfigInfo)
  1924. {
  1925. DBConnectionInfo info = (DBConnectionInfo)it.Value;
  1926. DataProvider.IDataProvider dataProvider = GetDataProvider(info.dbType);
  1927. Hashtable ht1 = (Hashtable)_connList[info.dbName];
  1928. foreach (DictionaryEntry pool in info.connectionPool)
  1929. {
  1930. Hashtable ht2 = (Hashtable)ht1[pool.Key];
  1931. lock (ht2)
  1932. {
  1933. ArrayList connList = ht2[0] as ArrayList;
  1934. Hashtable busyConnList = (Hashtable)ht2[1];
  1935. int connNumber = 0;
  1936. if (connList != null)
  1937. {
  1938. connNumber = connList.Count;
  1939. }
  1940. else
  1941. {
  1942. connList = new ArrayList();
  1943. ht2.Remove(0);
  1944. ht2.Add(0, connList);
  1945. }
  1946. if (busyConnList != null)
  1947. {
  1948. connNumber += busyConnList.Count;
  1949. }
  1950. if (connNumber < Convert.ToInt32(pool.Value))
  1951. {
  1952. cwl.WriteLog("有数据库连接意外销毁,增加数据库连接!", LogInfoLevel.Message, info.dbName, "FixConnections");
  1953. for (int i = connNumber; i < Convert.ToInt32(pool.Value); i++)
  1954. {
  1955. try
  1956. {
  1957. IDbConnection conn = dataProvider.CreateConnectionObject(info.connectionString);
  1958. conn.Open();
  1959. connList.Add(conn);
  1960. cwl.WriteLog("增加数据库连接" + info.dbName + " " + pool.Key + " " + i.ToString() + "成功!", LogInfoLevel.Message, info.dbName, "FixConnections");
  1961. }
  1962. catch (Exception ex)
  1963. {
  1964. cwl.WriteLog("增加数据库连接" + info.dbName + " " + pool.Key + " " + i.ToString() + "失败!", LogInfoLevel.Error, info.dbName, "FixConnections");
  1965. Console.WriteLine("增加数据库连接" + info.dbName + " " + pool.Key + " " + "失败!" + ex.Message + "\n");
  1966. break;
  1967. }
  1968. }
  1969. }
  1970. }
  1971. }
  1972. }
  1973. }
  1974. catch (Exception ex)
  1975. {
  1976. cwl.WriteLog(ex.Message, LogInfoLevel.Error, "", "FixConnections");
  1977. }
  1978. Thread.Sleep(3 * 60 * 1000);
  1979. }
  1980. }
  1981. private void CheckConnActive()
  1982. {
  1983. while (true)
  1984. {
  1985. try
  1986. {
  1987. if (_init)
  1988. {
  1989. foreach (DictionaryEntry it in _connList)
  1990. {
  1991. Hashtable ht1 = (Hashtable)it.Value;
  1992. string dbName = it.Key as string;
  1993. DBConnectionInfo info = (DBConnectionInfo)_dbConfigInfo[dbName];
  1994. DataProvider.IDataProvider dataProvider = GetDataProvider(info.dbType);
  1995. foreach (DictionaryEntry it2 in ht1)
  1996. {
  1997. ArrayList connList = ((Hashtable)it2.Value)[0] as ArrayList;
  1998. #region // 检查闲列表
  1999. //for ( int l = 0 ; l< connList.Count ;l++)
  2000. //{
  2001. // IDbConnection conn = connList[l] as IDbConnection ;
  2002. // if(conn!=null)
  2003. // {
  2004. // if(!dataProvider.Ping(ref conn) )
  2005. // {
  2006. // //Thread.Sleep( 1000);
  2007. // //if(!dataProvider.Ping(ref conn) )
  2008. // //{
  2009. // cwl.WriteLog("连接失效,重新连接中......", LogInfoLevel.Message, info.dbName, "CheckConnActive");
  2010. // Console.WriteLine(info.dbName + "连接失效,重新连接中......\n");
  2011. // //connList.Remove(conn);
  2012. // if (conn != null )
  2013. // {
  2014. // conn.Close();
  2015. // conn.Dispose();
  2016. // conn = null;
  2017. // GC.Collect();
  2018. // }
  2019. // try
  2020. // {
  2021. // conn = dataProvider.CreateConnectionObject(info.connectionString);
  2022. // conn.Open();
  2023. // connList[l] = conn;
  2024. // cwl.WriteLog("重连成功!", LogInfoLevel.Message, info.dbName, "CheckConnActive");
  2025. // Console.WriteLine(info.dbName + "重连成功!\n");
  2026. // }
  2027. // catch(Exception ex)
  2028. // {
  2029. // cwl.WriteLog("重连失败!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2030. // Console.WriteLine(info.dbName + "重连失败!" +ex.Message + "\n");
  2031. // }
  2032. // //}
  2033. // }
  2034. // }
  2035. // else
  2036. // {
  2037. // try
  2038. // {
  2039. // conn = dataProvider.CreateConnectionObject(info.connectionString);
  2040. // conn.Open();
  2041. // connList[l]= conn;
  2042. // Console.WriteLine(info.dbName + "重连成功!\n");
  2043. // cwl.WriteLog("重连成功!", LogInfoLevel.Message, info.dbName, "CheckConnActive");
  2044. // }
  2045. // catch(Exception ex)
  2046. // {
  2047. // Console.WriteLine("重连失败!" + ex.Message + "\n");
  2048. // cwl.WriteLog("重连失败!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2049. // }
  2050. // }
  2051. //}
  2052. #endregion
  2053. #region // 检查忙列表
  2054. if (((Hashtable)it2.Value).Count < 2) continue;
  2055. Hashtable busyConnList = ((Hashtable)it2.Value)[1] as Hashtable;
  2056. if (busyConnList != null)
  2057. {
  2058. Hashtable m_busyConnList = busyConnList.Clone() as Hashtable;
  2059. foreach (DictionaryEntry busyConn in m_busyConnList)
  2060. {
  2061. DateTime dt = ((CurrConnOperateInfo)busyConn.Value).dt;
  2062. DateTime t = DateTime.Now;
  2063. if ((string)it2.Key == "A")
  2064. {
  2065. t = dt.AddSeconds(_connLifeTimeA);
  2066. }
  2067. else if ((string)it2.Key == "B")
  2068. {
  2069. t = dt.AddSeconds(_connLifeTimeB);
  2070. }
  2071. else if ((string)it2.Key == "C")
  2072. {
  2073. t = dt.AddSeconds(_connLifeTimeC);
  2074. }
  2075. #region //判断是否已经超时
  2076. if (t.CompareTo(DateTime.Now) < 0)
  2077. {
  2078. IDbConnection conn = busyConn.Key as IDbConnection;
  2079. if (conn != null)
  2080. {
  2081. try
  2082. {
  2083. cwl.WriteLog("有连接超时,将关闭重连!||忙连接数:" + busyConnList.Count.ToString() + "||闲连接数:" + connList.Count.ToString()
  2084. + " SID:" + ((CurrConnOperateInfo)busyConn.Value).SID.ToString()
  2085. + " SQL:" + ((CurrConnOperateInfo)busyConn.Value).sqlstr
  2086. + " 执行开始时间:" + ((CurrConnOperateInfo)busyConn.Value).dt.ToLongTimeString()
  2087. + " 当前时间:" + DateTime.Now.ToLongTimeString(),
  2088. LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2089. busyConnList.Remove(conn);
  2090. conn.Close();
  2091. conn.Dispose();
  2092. conn = null;
  2093. GC.Collect();
  2094. conn = dataProvider.CreateConnectionObject(info.connectionString);
  2095. conn.Open();
  2096. if (connList == null)
  2097. {
  2098. connList = new ArrayList();
  2099. ht1.Remove(0);
  2100. ht1.Add(0, connList);
  2101. }
  2102. connList.Add(conn);
  2103. cwl.WriteLog("超时连接重连成功!||忙连接数:" + busyConnList.Count.ToString() + "||闲连接数:" + connList.Count.ToString(),
  2104. LogInfoLevel.Message, info.dbName, "CheckConnActive");
  2105. }
  2106. catch (Exception ex)
  2107. {
  2108. cwl.WriteLog("重连失败,丢失一个连接!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2109. Console.WriteLine("重连失败,丢失一个连接!" + ex.Message + "\n");
  2110. }
  2111. }
  2112. else
  2113. {
  2114. try
  2115. {
  2116. cwl.WriteLog("有连接失效,将关闭重连!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2117. Console.WriteLine(info.dbName + "有连接失效,将关闭重连!\n");
  2118. busyConnList.Remove(conn);
  2119. conn = dataProvider.CreateConnectionObject(info.connectionString);
  2120. conn.Open();
  2121. if (connList == null)
  2122. {
  2123. connList = new ArrayList();
  2124. ht1.Remove(0);
  2125. ht1.Add(0, connList);
  2126. }
  2127. connList.Add(conn);
  2128. }
  2129. catch (Exception ex)
  2130. {
  2131. cwl.WriteLog("重连失败,丢失一个连接!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2132. Console.WriteLine("重连失败,丢失一个连接!" + ex.Message + "\n");
  2133. }
  2134. }
  2135. }
  2136. #endregion
  2137. }
  2138. }
  2139. #endregion
  2140. }
  2141. }
  2142. }
  2143. }
  2144. catch (Exception ex)
  2145. {
  2146. cwl.WriteLog(ex.Message, LogInfoLevel.Error, "", "CheckConnActive");
  2147. // Console.WriteLine(ex.Message);
  2148. }
  2149. Thread.Sleep(1 * 60 * 1000);
  2150. }
  2151. }
  2152. */
  2153. #endregion
  2154. #region 变更代码 maliang 2011-10-19
  2155. private static object lockObj = new object();
  2156. private void ConnectionsListener()
  2157. {
  2158. while (true)
  2159. {
  2160. lock (lockObj)
  2161. {
  2162. CheckConnActive();
  2163. FixConnections();
  2164. Thread.Sleep(1 * 60 * 1000);
  2165. }
  2166. }
  2167. }
  2168. private void FixConnections()
  2169. {
  2170. try
  2171. {
  2172. foreach (DictionaryEntry it in _dbConfigInfo)
  2173. {
  2174. DBConnectionInfo info = (DBConnectionInfo)it.Value;
  2175. DataProvider.IDataProvider dataProvider = GetDataProvider(info.dbType);
  2176. Hashtable ht1 = (Hashtable)_connList[info.dbName];
  2177. foreach (DictionaryEntry pool in info.connectionPool)
  2178. {
  2179. Hashtable ht2 = (Hashtable)ht1[pool.Key];
  2180. lock (ht2)
  2181. {
  2182. ArrayList connList = ht2[0] as ArrayList;
  2183. Hashtable busyConnList = (Hashtable)ht2[1];
  2184. int connNumber = 0;
  2185. if (connList != null)
  2186. {
  2187. connNumber = connList.Count;
  2188. }
  2189. else
  2190. {
  2191. connList = new ArrayList();
  2192. ht2.Remove(0);
  2193. ht2.Add(0, connList);
  2194. }
  2195. if (busyConnList != null)
  2196. {
  2197. connNumber += busyConnList.Count;
  2198. }
  2199. if (connNumber < Convert.ToInt32(pool.Value))
  2200. {
  2201. cwl.WriteLog("有数据库连接意外销毁,增加数据库连接!", LogInfoLevel.Message, info.dbName, "FixConnections");
  2202. for (int i = connNumber; i < Convert.ToInt32(pool.Value); i++)
  2203. {
  2204. try
  2205. {
  2206. IDbConnection conn = dataProvider.CreateConnectionObject(info.connectionString);
  2207. conn.Open();
  2208. connList.Add(conn);
  2209. cwl.WriteLog("增加数据库连接" + info.dbName + " " + pool.Key + " " + i.ToString() + "成功!", LogInfoLevel.Message, info.dbName, "FixConnections");
  2210. }
  2211. catch (Exception ex)
  2212. {
  2213. cwl.WriteLog("增加数据库连接" + info.dbName + " " + pool.Key + " " + i.ToString() + "失败!", LogInfoLevel.Error, info.dbName, "FixConnections");
  2214. Console.WriteLine("增加数据库连接" + info.dbName + " " + pool.Key + " " + "失败!" + ex.Message + "\n");
  2215. break;
  2216. }
  2217. }
  2218. }
  2219. }
  2220. }
  2221. }
  2222. }
  2223. catch (Exception ex)
  2224. {
  2225. cwl.WriteLog(ex.Message, LogInfoLevel.Error, "", "FixConnections");
  2226. }
  2227. }
  2228. private void CheckConnActive()
  2229. {
  2230. try
  2231. {
  2232. if (_init)
  2233. {
  2234. foreach (DictionaryEntry it in _connList)
  2235. {
  2236. Hashtable ht1 = (Hashtable)it.Value;
  2237. string dbName = it.Key as string;
  2238. DBConnectionInfo info = (DBConnectionInfo)_dbConfigInfo[dbName];
  2239. DataProvider.IDataProvider dataProvider = GetDataProvider(info.dbType);
  2240. foreach (DictionaryEntry it2 in ht1)
  2241. {
  2242. ArrayList connList = ((Hashtable)it2.Value)[0] as ArrayList;
  2243. #region // 检查忙列表
  2244. if (((Hashtable)it2.Value).Count < 2) continue;
  2245. Hashtable busyConnList = ((Hashtable)it2.Value)[1] as Hashtable;
  2246. if (busyConnList != null)
  2247. {
  2248. Hashtable m_busyConnList = busyConnList.Clone() as Hashtable;
  2249. foreach (DictionaryEntry busyConn in m_busyConnList)
  2250. {
  2251. DateTime dt = ((CurrConnOperateInfo)busyConn.Value).dt;
  2252. DateTime t = DateTime.Now;
  2253. if ((string)it2.Key == "A")
  2254. {
  2255. t = dt.AddSeconds(_connLifeTimeA);
  2256. }
  2257. else if ((string)it2.Key == "B")
  2258. {
  2259. t = dt.AddSeconds(_connLifeTimeB);
  2260. }
  2261. else if ((string)it2.Key == "C")
  2262. {
  2263. t = dt.AddSeconds(_connLifeTimeC);
  2264. }
  2265. #region //判断是否已经超时
  2266. if (t.CompareTo(DateTime.Now) < 0)
  2267. {
  2268. IDbConnection conn = busyConn.Key as IDbConnection;
  2269. if (conn != null)
  2270. {
  2271. try
  2272. {
  2273. cwl.WriteLog("有连接超时,将关闭重连!||忙连接数:" + busyConnList.Count.ToString() + "||闲连接数:" + connList.Count.ToString()
  2274. + " SID:" + ((CurrConnOperateInfo)busyConn.Value).SID.ToString()
  2275. + " SQL:" + ((CurrConnOperateInfo)busyConn.Value).sqlstr
  2276. + " 执行开始时间:" + ((CurrConnOperateInfo)busyConn.Value).dt.ToLongTimeString()
  2277. + " 当前时间:" + DateTime.Now.ToLongTimeString(),
  2278. LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2279. busyConnList.Remove(conn);
  2280. conn.Close();
  2281. conn.Dispose();
  2282. conn = null;
  2283. GC.Collect();
  2284. conn = dataProvider.CreateConnectionObject(info.connectionString);
  2285. conn.Open();
  2286. if (connList == null)
  2287. {
  2288. connList = new ArrayList();
  2289. ht1.Remove(0);
  2290. ht1.Add(0, connList);
  2291. }
  2292. connList.Add(conn);
  2293. cwl.WriteLog("超时连接重连成功!||忙连接数:" + busyConnList.Count.ToString() + "||闲连接数:" + connList.Count.ToString(),
  2294. LogInfoLevel.Message, info.dbName, "CheckConnActive");
  2295. }
  2296. catch (Exception ex)
  2297. {
  2298. cwl.WriteLog("重连失败,丢失一个连接!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2299. Console.WriteLine("重连失败,丢失一个连接!" + ex.Message + "\n");
  2300. }
  2301. }
  2302. else
  2303. {
  2304. try
  2305. {
  2306. cwl.WriteLog("有连接失效,将关闭重连!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2307. Console.WriteLine(info.dbName + "有连接失效,将关闭重连!\n");
  2308. busyConnList.Remove(conn);
  2309. conn = dataProvider.CreateConnectionObject(info.connectionString);
  2310. conn.Open();
  2311. if (connList == null)
  2312. {
  2313. connList = new ArrayList();
  2314. ht1.Remove(0);
  2315. ht1.Add(0, connList);
  2316. }
  2317. connList.Add(conn);
  2318. }
  2319. catch (Exception ex)
  2320. {
  2321. cwl.WriteLog("重连失败,丢失一个连接!", LogInfoLevel.Error, info.dbName, "CheckConnActive");
  2322. Console.WriteLine("重连失败,丢失一个连接!" + ex.Message + "\n");
  2323. }
  2324. }
  2325. }
  2326. #endregion
  2327. }
  2328. }
  2329. #endregion
  2330. }
  2331. }
  2332. }
  2333. }
  2334. catch (Exception ex)
  2335. {
  2336. cwl.WriteLog(ex.Message, LogInfoLevel.Error, "", "CheckConnActive");
  2337. // Console.WriteLine(ex.Message);
  2338. }
  2339. }
  2340. #endregion
  2341. #region
  2342. //处理存储过程调用,打印相关参数值;
  2343. private string PraseProducePara(IDbCommand command)
  2344. {
  2345. string sRet = "";
  2346. if (command.Parameters.Count > 0)
  2347. foreach (IDataParameter idp in command.Parameters)
  2348. {
  2349. sRet += PraseOneParameter(idp.Value, 0, idp.ParameterName);
  2350. }
  2351. return sRet;
  2352. }
  2353. private string PraseOneParameter(object obj, int level, string obj_name)
  2354. {
  2355. /*if (_p.GetType().FullName.ToUpper() == "Oracle.DataAccess.Client.OracleParameter".ToUpper())
  2356. {
  2357. Oracle.DataAccess.Client.OracleParameter p1 = (Oracle.DataAccess.Client.OracleParameter)(_p);
  2358. if (p1.CollectionType == Oracle.DataAccess.Client.OracleCollectionType.PLSQLAssociativeArray)
  2359. {
  2360. }
  2361. }*/
  2362. string sRet = "";
  2363. string prefix = "".PadLeft(2 * level, ' ');
  2364. bool isEnumerable = false;
  2365. if (obj == null)
  2366. {
  2367. sRet += prefix + obj_name + ":= null;\r\n";
  2368. return sRet;
  2369. }
  2370. Type itype = obj.GetType();
  2371. PropertyInfo[] props = itype.GetProperties();
  2372. foreach (PropertyInfo p in props)
  2373. {
  2374. if (p.PropertyType.IsGenericType && p.PropertyType.GetInterface("IEnumerable", false) != null && typeof(string) == p.PropertyType.GetGenericArguments()[0])
  2375. {
  2376. isEnumerable = true;
  2377. }
  2378. }
  2379. if (isEnumerable)
  2380. {
  2381. int i = 1;
  2382. foreach (object o in (IEnumerable)obj)
  2383. {
  2384. sRet += string.Format("{0}{1}{2}\n", (level == 0 ? obj_name + "(" + i.ToString() + ") := " : ""), prefix, PraseOneParameter(o, level + 1, ""));
  2385. i++;
  2386. }
  2387. sRet += "}\r\n";
  2388. }
  2389. else if (itype.IsArray)
  2390. {
  2391. int i = 1;
  2392. foreach (object o in (IEnumerable)obj)
  2393. {
  2394. sRet += string.Format("{0}{1}{2}\n", (level == 0 ? obj_name + "(" + i.ToString() + ") := " : ""), prefix, PraseOneParameter(o, level + 1, ""));
  2395. i++;
  2396. }
  2397. if (sRet.Substring(sRet.Length - 2, 2) == "\r\n")
  2398. {
  2399. sRet = sRet.Remove(sRet.Length - 2);
  2400. }
  2401. sRet += "\r\n";
  2402. }
  2403. else
  2404. {
  2405. if (itype == typeof(string))
  2406. {
  2407. sRet += (level == 0 ? obj_name + " := " : "") + string.Format("{0}'{1}';\r\n", prefix, obj.ToString());
  2408. }
  2409. else
  2410. {
  2411. sRet += (level == 0 ? obj_name + " := " : "") + string.Format("{0}{1};\r\n", prefix, obj.ToString());
  2412. }
  2413. }
  2414. return sRet;
  2415. }
  2416. /* private string PraseOneParameter(object obj, int level, string obj_name)
  2417. {
  2418. string sRet = "";
  2419. string prefix = "".PadLeft(2 * level, ' ');
  2420. bool isEnumerable = false;
  2421. if (obj == null)
  2422. {
  2423. sRet += prefix + (level == 0 ? obj_name + ":" : "") + "'';\r\n";
  2424. return sRet;
  2425. }
  2426. Type itype = obj.GetType();
  2427. PropertyInfo[] props = itype.GetProperties();
  2428. foreach (PropertyInfo p in props)
  2429. {
  2430. if (p.PropertyType.IsGenericType && p.PropertyType.GetInterface("IEnumerable", false) != null && typeof(string) == p.PropertyType.GetGenericArguments()[0])
  2431. {
  2432. isEnumerable = true;
  2433. }
  2434. }
  2435. if (isEnumerable)
  2436. {
  2437. sRet += (level == 0 ? obj_name + ":\r\n" : "") + prefix + "{";
  2438. foreach (object o in (IEnumerable)obj)
  2439. {
  2440. sRet += PraseOneParameter(o, level + 1, "");
  2441. }
  2442. sRet += "}\r\n";
  2443. }
  2444. else if (itype.IsArray)
  2445. {
  2446. sRet += (level == 0 ? obj_name + ":\r\n" : "") + prefix + "{";
  2447. foreach (object o in (IEnumerable)obj)
  2448. {
  2449. sRet += PraseOneParameter(o, level + 1, "");
  2450. }
  2451. if (sRet.Substring(sRet.Length - 2, 2) == "\r\n")
  2452. {
  2453. sRet = sRet.Remove(sRet.Length - 2);
  2454. }
  2455. sRet += "}\r\n";
  2456. }
  2457. else
  2458. {
  2459. if (itype == typeof(string))
  2460. {
  2461. sRet += (level == 0 ? obj_name + ":" : "") + string.Format("{0}'{1}';\r\n", prefix, obj.ToString());
  2462. }
  2463. else
  2464. {
  2465. sRet += (level == 0 ? obj_name + ":" : "") + string.Format("{0}{1};\r\n", prefix, obj.ToString());
  2466. }
  2467. }
  2468. return sRet;
  2469. }
  2470. */
  2471. #endregion
  2472. ///////////////////////////////////////////////////////////////////////////////
  2473. ///私有数据成员
  2474. //////////////////////////////////////////////////////////////////////////////
  2475. //定义数据库连接信息
  2476. private struct DBConnectionInfo
  2477. {
  2478. public string dbName;
  2479. public string dbType;
  2480. public string connectionString;
  2481. // <Key = priority Value = maxConnectionNum/>
  2482. public Hashtable connectionPool;
  2483. };
  2484. // 存储当前连接的操作信息
  2485. private struct CurrConnOperateInfo
  2486. {
  2487. public DateTime dt;
  2488. public string sqlstr;
  2489. public int SID;
  2490. }
  2491. /// <summary>
  2492. /// 事务信息
  2493. /// </summary>
  2494. private struct TransInfo
  2495. {
  2496. public long dbManagerID;
  2497. public IDbConnection dbConnection;
  2498. public IDbTransaction dbTransaction;
  2499. public DateTime beginTime;
  2500. };
  2501. private void showsql(string sql)
  2502. {
  2503. //Console.WriteLine(sql+"\n");
  2504. }
  2505. #endregion
  2506. private static long[] _dbManagerID = new long[1] { 0 };//由DBProxy为每个DBManager对象分配的ID
  2507. //<Key = name Value DBConnectionInfo>
  2508. private Hashtable _dbConfigInfo;//数据库配置信息
  2509. private static Hashtable _connList = new Hashtable();
  2510. private Hashtable _transList = new Hashtable();
  2511. private Hashtable _dbList = new Hashtable();//每个DBManager对应的数据库信息
  2512. private double _connLifeTimeA;//数据库连接允许的最长无反应时间A级
  2513. private double _connLifeTimeB;//数据库连接允许的最长无反应时间B级
  2514. private double _connLifeTimeC;//数据库连接允许的最长无反应时间C级
  2515. private Thread _checkConnThread = null;//检查Conn是否有效
  2516. private Thread _fixConnThread = null;//检查Conn是否有足够数量
  2517. private Thread _ConnectionsListenerThread;//检查Conn是否有效和是否有足够数量
  2518. private long _reference = 0;//DBProxy对象实例数
  2519. private bool _init = false;
  2520. public delegate void ShowLogDelegate(string log);
  2521. public event ShowLogDelegate ShowLogEvent;
  2522. private void ShowLog(string log)
  2523. {
  2524. if (ShowLogEvent != null)
  2525. {
  2526. ShowLogEvent(log);
  2527. }
  2528. }
  2529. public void SetLogHandler(ShowLogDelegate _handle)
  2530. {
  2531. ShowLogEvent += _handle;
  2532. }
  2533. }
  2534. }