DataHelper.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. using Oracle.ManagedDataAccess.Client;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Text;
  6. using UAS_MES_NEW.PublicMethod;
  7. namespace UAS_MES_NEW.DataOperate
  8. {
  9. class DataHelper
  10. {
  11. //系统默认的的连接字符串
  12. private string ConnectionStrings = Properties.Settings.Default.Properties["MES"].DefaultValue.ToString();
  13. //用户选择的数据库的连接字符串
  14. public static string DBConnectionString;
  15. public static OracleConnection connection = null;
  16. OracleCommand command = null;
  17. int ReconnectTime = 0;
  18. /// <summary>
  19. /// 执行构造函数的时候打开数据库的链接
  20. /// </summary>
  21. public DataHelper()
  22. {
  23. try
  24. {
  25. //如果选择的是默认数据则直接用配置文件的信息连接,否则选择数据库的账套信息
  26. if (DBConnectionString == null || DBConnectionString == ConnectionStrings)
  27. connection = new OracleConnection(ConnectionStrings);
  28. else
  29. connection = new OracleConnection(DBConnectionString);
  30. connection.Open();
  31. }
  32. catch (Exception e) { LogManager.DoLog(e.Message); }
  33. }
  34. /// <summary>
  35. /// 根据表名获取该表字段数据类型
  36. /// </summary>
  37. public DataTable GetColumnDataType(string TableName)
  38. {
  39. DataTable dt = new DataTable();
  40. command = new OracleCommand("select Column_Name,Data_Type from cols where TABLE_name=upper('" + TableName + "')", connection);
  41. Reconnect(command);
  42. OracleDataAdapter ad = new OracleDataAdapter(command);
  43. ad.Fill(dt);
  44. ad.Dispose();
  45. return dt;
  46. }
  47. /// <summary>
  48. /// 获取第一行第一列的信息
  49. /// </summary>
  50. public object getFieldDataByCondition(string TableName, string Field, string Condition)
  51. {
  52. DataTable dt = new DataTable();
  53. string sql = "select " + Field + " from " + TableName + " where " + Condition;
  54. command = new OracleCommand(sql, connection);
  55. //LogManager.DoSQLLog(sql.ToString());
  56. Console.WriteLine(sql);
  57. Reconnect(command);
  58. OracleDataAdapter ad = new OracleDataAdapter();
  59. ad.SelectCommand = command;
  60. try
  61. {
  62. ad.Fill(dt);
  63. }
  64. catch (Exception)
  65. {
  66. connection = new OracleConnection(DBConnectionString);
  67. connection.Open();
  68. command = new OracleCommand(sql, connection);
  69. ad = new OracleDataAdapter();
  70. ad.SelectCommand = command;
  71. ad.Fill(dt);
  72. }
  73. ad.Dispose();
  74. if (dt.Rows.Count > 0)
  75. {
  76. return dt.Rows[0][0];
  77. }
  78. else
  79. {
  80. return "";
  81. }
  82. }
  83. /// <summary>
  84. /// 执行打印的SQL
  85. /// </summary>
  86. /// <param name="SQL">SQL语句</param>
  87. /// <param name="Parameters">动态添加的参数,主要根据条码枪扫描获取</param>
  88. /// <returns></returns>
  89. public object ExecutePrintSQL(string SQL, params string[] Parameters)
  90. {
  91. //按照?拆分数据,然后以:Param替换问号,同时添加参数
  92. string[] Param = SQL.Split('?');
  93. int ParamNum = Param.Length - 1;
  94. //条码打印必然存在需要维护的参数
  95. if (ParamNum > 0)
  96. {
  97. StringBuilder sb = new StringBuilder();
  98. for (int i = 0; i < ParamNum; i++)
  99. {
  100. sb.Append(Param[i] + ":Param" + i);
  101. }
  102. command = new OracleCommand(sb.ToString(), connection);
  103. for (int i = 0; i < ParamNum; i++)
  104. {
  105. command.Parameters.Add("Param" + i, OracleDbType.Varchar2, Parameters[i], ParameterDirection.Input);
  106. }
  107. OracleDataAdapter ad = new OracleDataAdapter(command);
  108. DataTable dt = new DataTable();
  109. ad.Fill(dt);
  110. ad.Dispose();
  111. return dt;
  112. }
  113. return "参数错误,请检查SQL语句";
  114. }
  115. /// <summary>
  116. /// 获取指定表的记录的条数 ,带条件
  117. /// </summary>
  118. /// <returns></returns>
  119. public int getRowCount(string TableName, string Condition)
  120. {
  121. DataTable dt = new DataTable();
  122. string sql = "select count(1) from " + TableName + " where " + Condition;
  123. command = new OracleCommand(sql, connection);
  124. Reconnect(command);
  125. OracleDataAdapter ad = new OracleDataAdapter(command);
  126. ad.Fill(dt);
  127. ad.Dispose();
  128. return int.Parse(dt.Rows[0][0].ToString());
  129. }
  130. /// <summary>
  131. /// 获取指定表的记录的条数 ,不带条件
  132. /// </summary>
  133. /// <param name="TableName"></param>
  134. /// <returns></returns>
  135. public int getRowCount(string TableName)
  136. {
  137. DataTable dt = new DataTable();
  138. string sql = "select count(1) from " + TableName;
  139. command = new OracleCommand(sql, connection);
  140. Reconnect(command);
  141. OracleDataAdapter ad = new OracleDataAdapter(command);
  142. ad.Fill(dt);
  143. ad.Dispose();
  144. return int.Parse(dt.Rows[0][0].ToString());
  145. }
  146. /// <summary>
  147. /// 通过表名和获取单行的记录
  148. /// </summary>
  149. public DataTable getFieldsDataByCondition(string TableName, string[] Fields, string Condition)
  150. {
  151. DataTable dt = new DataTable();
  152. string sql = "select ";
  153. sql += AddField(Fields);
  154. sql += " from " + TableName + " where " + Condition + " and rownum=1";
  155. command = new OracleCommand(sql, connection);
  156. Reconnect(command);
  157. OracleDataAdapter ad = new OracleDataAdapter(command);
  158. try
  159. {
  160. ad.Fill(dt);
  161. }
  162. catch (Exception)
  163. {
  164. connection = new OracleConnection(DBConnectionString);
  165. connection.Open();
  166. command = new OracleCommand(sql, connection);
  167. ad = new OracleDataAdapter();
  168. ad.SelectCommand = command;
  169. ad.Fill(dt);
  170. }
  171. ad.Dispose();
  172. return dt;
  173. }
  174. /// <summary>
  175. /// 将DataTable导入到指定的表中
  176. /// </summary>
  177. /// <param name="DataTable"></param>
  178. /// <param name="TableName"></param>
  179. public void InsertDataTable(DataTable DataTable, string TableName)
  180. {
  181. for (int i = 0; i < DataTable.Rows.Count; i++)
  182. {
  183. for (int j = 0; j < DataTable.Columns.Count; j++)
  184. {
  185. }
  186. }
  187. }
  188. /// <summary>
  189. /// 按分页获取数据
  190. /// </summary>
  191. /// <param name="TableName">表名</param>
  192. /// <param name="Fields">查询字段</param>
  193. /// <param name="CurrentPage">当前页面</param>
  194. /// <param name="PageSize">页面展示条数</param>
  195. /// <param name="Caller"></param>
  196. /// <returns></returns>
  197. // SELECT * FROM (SELECT A.* FROM (SELECT* FROM datalist) A WHERE ROWNUM <= 50) WHERE ROWNUM >= 21
  198. public DataTable getFieldsDatasByPageing(string TableName, string Fields, int CurrentPage, int PageSize, string Caller, params string[] condition)
  199. {
  200. DataTable dt = new DataTable();
  201. StringBuilder sql = new StringBuilder();
  202. //先查询出配置出去的列
  203. //获取查询的列
  204. string[] caption = GetCaptionFromField(Fields);
  205. //获取对应列的描述
  206. string[] field = GetField(Fields);
  207. sql.Append(" select * from (select RowNum RN, A.* from (select ");
  208. sql.Append(AddField(caption));
  209. if (condition.Length > 0)
  210. {
  211. if (condition[0] != null && condition[0].Trim() != "")
  212. sql.Append(" from " + TableName + " where " + condition[0] + " ) A where ROWNUM <=" + CurrentPage * PageSize + ") where RN>" + (CurrentPage - 1) * PageSize);
  213. else
  214. sql.Append(" from " + TableName + ") A where ROWNUM <= " + CurrentPage * PageSize + ") where RN> " + (CurrentPage - 1) * PageSize);
  215. }
  216. command = new OracleCommand(sql.ToString(), connection);
  217. Reconnect(command);
  218. OracleDataAdapter ad = new OracleDataAdapter(command);
  219. ad.Fill(dt);
  220. ad.Dispose();
  221. dt.Columns.RemoveAt(0);
  222. foreach (DataColumn dc in dt.Columns)
  223. {
  224. dc.ColumnName = field[dt.Columns.IndexOf(dc)];
  225. dc.Caption = caption[dt.Columns.IndexOf(dc)];
  226. }
  227. return dt;
  228. }
  229. /// <summary>
  230. /// 通过表名,字段和条件获取DataTable类型的数据
  231. /// </summary>
  232. public DataTable getFieldsDatasByCondition(string TableName, string[] Fields, string Condition)
  233. {
  234. DataTable dt = new DataTable();
  235. string sql = "select ";
  236. sql += AddField(Fields);
  237. sql += " from " + TableName + " where " + Condition;
  238. command = new OracleCommand(sql, connection);
  239. Reconnect(command);
  240. OracleDataAdapter ad = new OracleDataAdapter(command);
  241. try
  242. {
  243. ad.Fill(dt);
  244. }
  245. catch (Exception)
  246. {
  247. connection = new OracleConnection(DBConnectionString);
  248. connection.Open();
  249. command = new OracleCommand(sql, connection);
  250. ad = new OracleDataAdapter();
  251. ad.SelectCommand = command;
  252. ad.Fill(dt);
  253. }
  254. ad.Dispose();
  255. return dt;
  256. }
  257. /// <summary>
  258. /// 通过表名,字段获取DataTable类型的数据
  259. /// </summary>
  260. public DataTable getFieldsDatas(string TableName, string Fields)
  261. {
  262. DataTable dt = new DataTable();
  263. string sql = "select ";
  264. sql += Fields;
  265. sql += " from " + TableName;
  266. command = new OracleCommand(sql, connection);
  267. Reconnect(command);
  268. OracleDataAdapter ad = new OracleDataAdapter(command);
  269. ad.SelectCommand = command;
  270. try
  271. {
  272. ad.Fill(dt);
  273. }
  274. catch (Exception)
  275. {
  276. connection = new OracleConnection(DBConnectionString);
  277. connection.Open();
  278. command = new OracleCommand(sql, connection);
  279. ad = new OracleDataAdapter();
  280. ad.SelectCommand = command;
  281. ad.Fill(dt);
  282. }
  283. ad.Dispose();
  284. return dt;
  285. }
  286. /// <summary>
  287. /// 根据DataTable和指定的表名更新数据,如果需要保存新增的数据则需要传递一条Insert的SQL
  288. /// </summary>
  289. /// <param name="DataTable"></param>
  290. /// <param name="TableName"></param>
  291. /// <param name="Condition"></param>
  292. public void UpDateTableByCondition(DataTable DataTable, string TableName, string PrimaryKey, params string[] sql)
  293. {
  294. if (DataTable == null)
  295. {
  296. return;
  297. }
  298. StringBuilder sb = new StringBuilder();
  299. //预防插入的DataTable中存在不属于该表的列,在进行下一步操作之前全部剔除
  300. DataTable data = (DataTable)ExecuteSql("select Column_Name,Data_Type from cols where TABLE_name=upper('" + TableName + "')", "select");
  301. //将所有的字段拼接起来
  302. for (int i = 0; i < data.Rows.Count; i++)
  303. {
  304. sb.Append("#" + data.Rows[i]["Column_Name"].ToString());
  305. }
  306. //移除掉所有不属于该表的列
  307. for (int i = DataTable.Columns.Count - 1; i >= 0; i--)
  308. {
  309. if (!sb.ToString().Contains(DataTable.Columns[i].ColumnName.ToUpper()))
  310. {
  311. DataTable.Columns.RemoveAt(i);
  312. }
  313. }
  314. sb.Clear();
  315. //计算有多少个是新加的行,根据主键为空来进行判断
  316. int NewRowCount = 0;
  317. for (int i = 0; i < DataTable.Rows.Count; i++)
  318. {
  319. if (DataTable.Rows[i][PrimaryKey] == null || DataTable.Rows[i][PrimaryKey].ToString() == "")
  320. {
  321. NewRowCount = NewRowCount + 1;
  322. }
  323. }
  324. if (sql.Length > 0)
  325. {
  326. if (NewRowCount > 0)
  327. {
  328. //获取参数的个数
  329. int paramsNum = sql[0].Split(':').Length - 1;
  330. //解析参数的数据
  331. string[] param = GetParamFromSQL(sql[0]);
  332. //新建一个二维数组去
  333. string[][] param_array = new string[paramsNum][];
  334. //实例化每个一维数组
  335. for (int i = 0; i < paramsNum; i++)
  336. {
  337. param_array[i] = new string[NewRowCount];
  338. }
  339. //设置每列参数的索引
  340. int num = 0;
  341. //变量所有的行,如果有主键为空的则移除,不为空的进行参数的拼接
  342. for (int i = DataTable.Rows.Count - 1; i >= 0; i--)
  343. {
  344. if (DataTable.Rows[i][PrimaryKey] == null || DataTable.Rows[i][PrimaryKey].ToString() == "")
  345. {
  346. //当为新添加行的时候才去设置参数,设置过后索引+1
  347. for (int j = 0; j < paramsNum; j++)
  348. {
  349. param_array[j][num] = DataTable.Rows[i][param[j]].ToString();
  350. }
  351. DataTable.Rows.RemoveAt(i);
  352. num++;
  353. }
  354. }
  355. BatchInsertDataTable(sql[0], param, param_array);
  356. }
  357. }
  358. //不是新增行的启用更新的方法
  359. sb.Append("update " + TableName + " set ");
  360. //拼接语句,特殊处理日期
  361. foreach (DataColumn dc in DataTable.Columns)
  362. {
  363. if (!dc.DataType.ToString().Equals("System.DateTime"))
  364. {
  365. sb.Append(dc.Caption + "=:" + dc.Caption + ",");
  366. }
  367. else
  368. {
  369. sb.Append(dc.Caption + "=:" + dc.Caption + ",");
  370. }
  371. }
  372. sb.Remove(sb.Length - 1, 1);
  373. sb.Append(" where " + PrimaryKey + "=:" + PrimaryKey);
  374. command = new OracleCommand(sb.ToString(), connection);
  375. OracleDataAdapter ad = new OracleDataAdapter(command);
  376. // 参数的长度是DataTable的行数决定的
  377. command.ArrayBindCount = DataTable.Rows.Count;
  378. //默认全部是Varchar2类型的
  379. OracleDbType ob = OracleDbType.Varchar2;
  380. for (int i = 0; i < DataTable.Columns.Count; i++)
  381. {
  382. object[] param = new object[DataTable.Rows.Count];
  383. for (int j = 0; j < DataTable.Rows.Count; j++)
  384. {
  385. DateTime dt = DateTime.Now;
  386. if (DateTime.TryParse(DataTable.Rows[j][i].ToString(), out dt))
  387. {
  388. param[j] = dt;
  389. ob = OracleDbType.Date;
  390. }
  391. else
  392. {
  393. ob = OracleDbType.Varchar2;
  394. param[j] = DataTable.Rows[j][i];
  395. }
  396. }
  397. //添加批量更新的参数
  398. command.Parameters.Add(new OracleParameter(DataTable.Columns[i].Caption, ob, param, ParameterDirection.Input));
  399. }
  400. ad.UpdateCommand = command;
  401. ad.Update(DataTable);
  402. ad.Dispose();
  403. }
  404. /// <summary>
  405. /// 获取DbFind的数据的DataTable的结构
  406. /// </summary>
  407. /// <param name="field"></param>
  408. /// <param name="caller"></param>
  409. /// <returns></returns>
  410. public DataTable GetDbFindDataTable(string field, string caller)
  411. {
  412. string sql = "select * from dbfindsetui where ds_caller='" + caller + "' and ds_whichui='" + field + "'";
  413. DataTable dt = (DataTable)ExecuteSql(sql, "select");
  414. if (dt.Rows.Count != 0)
  415. {
  416. //通过#号分割字段
  417. string[] dbfield = dt.Rows[0]["ds_findtoui"].ToString().Split('#');
  418. string[] cnfield = dt.Rows[0]["ds_dbcaption"].ToString().Split('#');
  419. //获取查询要查询的Table
  420. string dbtable = dt.Rows[0]["ds_tables"].ToString();
  421. //拼接查询的字段
  422. for (int i = 0; i < dbfield.Length; i++)
  423. {
  424. dbfield[i] = dbfield[i].Split(',')[0];
  425. }
  426. //新建一个空的DataTable
  427. DataTable dt1 = new DataTable();
  428. //往空的DataTable添加结构,ColumnName是中文,Caption是实际的字段名称
  429. for (int i = 0; i < cnfield.Length; i++)
  430. {
  431. dt1.Columns.Add(cnfield[i]);
  432. dt1.Columns[i].Caption = dbfield[i];
  433. }
  434. //返回一个带有结构的空的DataTable
  435. //DbFind.BindTable1 = dbtable;
  436. return dt1;
  437. }
  438. else
  439. {
  440. return null;
  441. }
  442. }
  443. /// <summary>
  444. /// 检测内容是否存在
  445. /// </summary>
  446. /// <param name="TableName"></param>
  447. /// <param name="Condition"></param>
  448. /// <returns></returns>
  449. public bool CheckExist(string TableName, string Condition)
  450. {
  451. string sql = "select count(1) from " + TableName + " where " + Condition;
  452. command = new OracleCommand(sql, connection);
  453. LogManager.DoSQLLog(sql.ToString());
  454. Reconnect(command);
  455. OracleDataAdapter ad = new OracleDataAdapter(command);
  456. DataTable dt = new DataTable();
  457. try
  458. {
  459. ad.Fill(dt);
  460. }
  461. catch (Exception)
  462. {
  463. connection = new OracleConnection(DBConnectionString);
  464. connection.Open();
  465. command = new OracleCommand(sql, connection);
  466. ad = new OracleDataAdapter();
  467. ad.SelectCommand = command;
  468. ad.Fill(dt);
  469. }
  470. ad.Dispose();
  471. Console.WriteLine(dt.Rows[0][0].ToString());
  472. Console.WriteLine(int.Parse(dt.Rows[0][0].ToString()) > 0);
  473. return int.Parse(dt.Rows[0][0].ToString()) > 0;
  474. }
  475. /// <summary>
  476. /// 直接执行SQL,同时传入SQL的类型
  477. /// </summary>
  478. /// <param name="SQL"></param>
  479. /// <param name="Type"></param>
  480. /// <returns></returns>
  481. public object ExecuteSql(string SQL, string Type, params object[] names)
  482. {
  483. object result = null;
  484. command = new OracleCommand(SQL, connection);
  485. Reconnect(command);
  486. //用来拼接参数的
  487. if (names.Length > 0)
  488. {
  489. string[] par = SQL.Split(':');
  490. //用来存参数的数组
  491. StringBuilder[] addpar = new StringBuilder[par.Length - 1];
  492. for (int i = 0; i < par.Length - 1; i++)
  493. {
  494. //新建一个char类型的数组用来存储每个字节的变量
  495. char[] c = par[i + 1].ToCharArray();
  496. addpar[i] = new StringBuilder();
  497. for (int j = 0; j < c.Length; j++)
  498. {
  499. if (c[j] != ' ' && c[j] != ',' && c[j] != ')')
  500. {
  501. addpar[i].Append(c[j]);
  502. }
  503. else
  504. {
  505. break;
  506. }
  507. }
  508. }
  509. for (int i = 0; i < addpar.Length; i++)
  510. command.Parameters.Add(new OracleParameter(addpar[i].ToString(), OracleDbType.Varchar2, names[i], ParameterDirection.Input));
  511. }
  512. LogManager.DoSQLLog(SQL.ToString());
  513. Console.WriteLine(SQL);
  514. switch (Type.ToUpper())
  515. {
  516. case "SELECT":
  517. OracleDataAdapter ad = new OracleDataAdapter(command);
  518. result = new DataTable();
  519. try
  520. {
  521. ad.Fill((DataTable)result);
  522. }
  523. catch (Exception)
  524. {
  525. connection = new OracleConnection(DBConnectionString);
  526. connection.Open();
  527. command = new OracleCommand(SQL, connection);
  528. ad = new OracleDataAdapter();
  529. ad.SelectCommand = command;
  530. ad.Fill((DataTable)result);
  531. }
  532. break;
  533. case "DELETE":
  534. try
  535. {
  536. result = command.ExecuteNonQuery();
  537. }
  538. catch (Exception)
  539. {
  540. command.Connection = new OracleConnection(DBConnectionString);
  541. command.Connection.Open();
  542. result = command.ExecuteNonQuery();
  543. }
  544. break;
  545. case "UPDATE":
  546. try
  547. {
  548. result = command.ExecuteNonQuery();
  549. }
  550. catch (Exception)
  551. {
  552. command.Connection = new OracleConnection(DBConnectionString);
  553. command.Connection.Open();
  554. result = command.ExecuteNonQuery();
  555. }
  556. break;
  557. case "INSERT":
  558. try
  559. {
  560. result = command.ExecuteNonQuery();
  561. }
  562. catch (Exception)
  563. {
  564. command.Connection = new OracleConnection(DBConnectionString);
  565. command.Connection.Open();
  566. result = command.ExecuteNonQuery();
  567. }
  568. break;
  569. }
  570. return result;
  571. }
  572. /// <summary>
  573. /// 为了同步BS端的条码维护,检测时允许问号的存在,在检测时默认将问号换成:Param参数
  574. /// </summary>
  575. /// <param name="SQL"></param>
  576. public void CheckSQL(string SQL)
  577. {
  578. SQL = SQL.Replace("?", ":Param");
  579. command = new OracleCommand(SQL, connection);
  580. command.ExecuteNonQuery();
  581. }
  582. public int GetDistinctRowCount(string TableName, string Field)
  583. {
  584. DataTable dt = new DataTable();
  585. string sql = "select distinct count('" + Field + "') from " + TableName;
  586. command = new OracleCommand(sql, connection);
  587. Reconnect(command);
  588. OracleDataAdapter ad = new OracleDataAdapter(command);
  589. try
  590. {
  591. ad.Fill(dt);
  592. }
  593. catch (Exception)
  594. {
  595. connection = new OracleConnection(DBConnectionString);
  596. connection.Open();
  597. command = new OracleCommand(sql, connection);
  598. ad = new OracleDataAdapter();
  599. ad.SelectCommand = command;
  600. ad.Fill(dt);
  601. }
  602. ad.Dispose();
  603. return int.Parse(dt.Rows[0][0].ToString());
  604. }
  605. /// <summary>
  606. /// 根据Caller获取流水号
  607. /// </summary>
  608. /// <param name="Caller"></param>
  609. /// <returns></returns>
  610. public string GetSerialNumberByCaller(string Caller)
  611. {
  612. string SerialNumber = getFieldDataByCondition("MaxNumbers", "mn_number", "mn_tablename='" + Caller + "'").ToString();
  613. UpdateByCondition("MaxNumbers", "mn_number=mn_number+1", "mn_tablename='" + Caller + "'");
  614. return SerialNumber;
  615. }
  616. /// <summary>
  617. /// 根据主键ID删除表的数据
  618. /// </summary>
  619. /// <param name="TableName">表名</param>
  620. /// <param name="ID">主键</param>
  621. /// <param name="DeleteID">需要删除主键ID的数组</param>
  622. public void DeleteDataByID(string TableName, string ID, string[] DeleteID)
  623. {
  624. string sql = "delete from " + TableName + " where " + ID + " =:DeleteID";
  625. command = new OracleCommand(sql, connection);
  626. Reconnect(command);
  627. command.ArrayBindCount = DeleteID.Length;
  628. command.Parameters.Add(new OracleParameter("DeleteID", OracleDbType.Long, DeleteID, ParameterDirection.Input));
  629. try
  630. {
  631. command.ExecuteNonQuery();
  632. }
  633. catch (Exception)
  634. {
  635. command.Connection = new OracleConnection(DBConnectionString);
  636. command.Connection.Open();
  637. command.ExecuteNonQuery();
  638. }
  639. }
  640. /// <summary>
  641. /// 通过序列的名称获取序列
  642. /// </summary>
  643. /// <param name="SeqName"></param>
  644. /// <returns></returns>
  645. public string GetSEQ(string SeqName)
  646. {
  647. DataTable dt = new DataTable();
  648. dt = (DataTable)ExecuteSql("SELECT " + SeqName + ".NEXTVAL FROM DUAL", "select");
  649. return dt.Rows[0][0].ToString();
  650. }
  651. /// <summary>
  652. /// 通过序列的名称获取序列
  653. /// </summary>
  654. /// <param name="SeqName"></param>
  655. /// <returns></returns>
  656. public string[] GetSEQ(string SeqName, int Num)
  657. {
  658. DataTable dt = new DataTable();
  659. dt = (DataTable)ExecuteSql("SELECT " + SeqName + ".nextval FROM DUAL CONNECT BY LEVEL<=" + Num, "select");
  660. string[] SerialNum = new string[dt.Rows.Count];
  661. for (int i = 0; i < dt.Rows.Count; i++)
  662. {
  663. SerialNum[i] = dt.Rows[i][0].ToString();
  664. }
  665. return SerialNum;
  666. }
  667. public void SaveDataTable(DataTable dt, string TableName, string ID, params string[] sql)
  668. {
  669. if (dt == null)
  670. {
  671. return;
  672. }
  673. StringBuilder sb = new StringBuilder();
  674. //预防插入的DataTable中存在不属于该表的列,在进行下一步操作之前全部剔除
  675. DataTable data = (DataTable)ExecuteSql("select Column_Name,Data_Type from cols where TABLE_name=upper('" + TableName + "')", "select");
  676. //将所有的字段拼接起来
  677. for (int i = 0; i < data.Rows.Count; i++)
  678. {
  679. sb.Append("#" + data.Rows[i]["Column_Name"].ToString());
  680. }
  681. //移除掉所有不属于该表的列
  682. for (int i = dt.Columns.Count - 1; i >= 0; i--)
  683. {
  684. if (!sb.ToString().Contains(dt.Columns[i].ColumnName.ToUpper()))
  685. {
  686. dt.Columns.RemoveAt(i);
  687. }
  688. }
  689. sb.Clear();
  690. //计算有多少个是新加的行,根据主键为空来进行判断
  691. int NewRowCount = 0;
  692. for (int i = 0; i < dt.Rows.Count; i++)
  693. {
  694. if (dt.Rows[i][ID] == null || dt.Rows[i][ID].ToString() == "")
  695. {
  696. NewRowCount = NewRowCount + 1;
  697. }
  698. }
  699. if (sql.Length > 0)
  700. {
  701. if (NewRowCount > 0)
  702. {
  703. //获取参数的个数
  704. int paramsNum = sql[0].Split(':').Length - 1;
  705. //解析参数的数据
  706. string[] param = GetParamFromSQL(sql[0]);
  707. //新建一个二维数组去
  708. string[][] param_array = new string[paramsNum][];
  709. //实例化每个一维数组
  710. for (int i = 0; i < paramsNum; i++)
  711. {
  712. param_array[i] = new string[NewRowCount];
  713. }
  714. //设置每列参数的索引
  715. int num = 0;
  716. //变量所有的行,如果有主键为空的则移除,不为空的进行参数的拼接
  717. for (int i = dt.Rows.Count - 1; i >= 0; i--)
  718. {
  719. if (dt.Rows[i][ID] == null || dt.Rows[i][ID].ToString() == "")
  720. {
  721. //当为新添加行的时候才去设置参数,设置过后索引+1
  722. for (int j = 0; j < paramsNum; j++)
  723. {
  724. param_array[j][num] = dt.Rows[i][param[j]].ToString();
  725. }
  726. dt.Rows.RemoveAt(i);
  727. num++;
  728. }
  729. }
  730. BatchInsertDataTable(sql[0], param, param_array);
  731. }
  732. }
  733. sb.Clear();
  734. sb.Append("update " + TableName + " set ");
  735. int ColumnCount = dt.Columns.Count;
  736. int RowCount = dt.Rows.Count;
  737. //存数据的参数
  738. List<string[]> Parameter = new List<string[]>();
  739. //存参数名的参数
  740. string[] ParName = new string[ColumnCount];
  741. for (int i = 0; i < ColumnCount; i++)
  742. {
  743. ParName[i] = dt.Columns[i].ColumnName;
  744. if (i == dt.Columns.Count - 1)
  745. sb.Append(dt.Columns[i].ColumnName + "=:" + dt.Columns[i].ColumnName);
  746. else
  747. sb.Append(dt.Columns[i].ColumnName + "=:" + dt.Columns[i].ColumnName + ",");
  748. }
  749. sb.Append(" where " + ID + " =:" + ID);
  750. //先添加参数
  751. Parameter.Add(ParName);
  752. //添加参数的具体内容
  753. for (int i = 0; i < ColumnCount; i++)
  754. {
  755. string[] par = new string[RowCount];
  756. for (int j = 0; j < RowCount; j++)
  757. {
  758. par[j] = dt.Rows[j][i].ToString();
  759. }
  760. Parameter.Add(par);
  761. }
  762. BatchInsert(sb.ToString(), Parameter.ToArray());
  763. }
  764. /// <summary>
  765. /// 批量通过SQL来执行插入操作 ,参数的第一个数一个string[]数组,用来传递需要添加的参数的名称
  766. /// 之后的是名称参数数组对应的 ,所有的插入参数数据长度必须是一致的
  767. /// </summary>
  768. /// <param name="sql"></param>
  769. /// <param name="names"></param>
  770. public void BatchInsert(string sql, params object[][] names)
  771. {
  772. command = new OracleCommand(sql, connection);
  773. Reconnect(command);
  774. command.ArrayBindCount = names[1].Length;
  775. //因为第一个数组保存的是参数的名称,所以循环从1而不是0开始
  776. //将第一个数组的下标固定为0作为循环添加的参数的名称
  777. for (int i = 1; i <= names[0].Length; i++)
  778. {
  779. command.Parameters.Add(new OracleParameter(names[0][i - 1].ToString(), OracleDbType.Varchar2, names[i], ParameterDirection.Input));
  780. }
  781. try
  782. {
  783. command.ExecuteNonQuery();
  784. }
  785. catch (Exception)
  786. {
  787. command.Connection = new OracleConnection(DBConnectionString);
  788. command.Connection.Open();
  789. command.ExecuteNonQuery();
  790. }
  791. }
  792. public void BatchInsertDataTable(string sql, string[] param, params object[][] param1)
  793. {
  794. command = new OracleCommand(sql, connection);
  795. Reconnect(command);
  796. command.ArrayBindCount = param1[0].Length;
  797. //因为第一个数组保存的是参数的名称,所以循环从1而不是0开始
  798. //将第一个数组的下标固定为0作为循环添加的参数的名称
  799. for (int i = 0; i < param.Length; i++)
  800. {
  801. command.Parameters.Add(new OracleParameter(param[i].ToString(), OracleDbType.Varchar2, param1[i], ParameterDirection.Input));
  802. }
  803. try
  804. {
  805. command.ExecuteNonQuery();
  806. }
  807. catch (Exception)
  808. {
  809. command.Connection = new OracleConnection(DBConnectionString);
  810. command.Connection.Open();
  811. command.ExecuteNonQuery();
  812. }
  813. }
  814. /// <summary>
  815. /// 取Configs表中的配置,进行该客户是否执行某个操作
  816. /// </summary>
  817. /// <param name="Code"></param>
  818. /// <param name="Caller"></param>
  819. /// <returns></returns>
  820. public object GetConfig(string Code, string Caller)
  821. {
  822. DataTable dt = new DataTable();
  823. string sql = "select Data from configs where code='" + Code + "' and caller='" + Caller + "'";
  824. dt = (DataTable)ExecuteSql(sql, "select");
  825. if (dt.Rows.Count == 0)
  826. {
  827. return "";
  828. }
  829. else
  830. {
  831. return dt.Rows[0]["Data"];
  832. }
  833. }
  834. //将数据类型的列类型转换为DataTable
  835. public DataTable DataTypeColumnToDataTable(DataTable dt)
  836. {
  837. DataTable dt1 = new DataTable();
  838. dt1.Rows.Add();
  839. foreach (DataRow dr in dt.Rows)
  840. {
  841. dt1.Columns.Add(dr[0].ToString());
  842. int index = dt.Rows.IndexOf(dr);
  843. if (dr[1].ToString() == "NUMBER")
  844. {
  845. dt1.Rows[0][index] = 0;
  846. }
  847. if (dr[1].ToString() == "VARCHAR2")
  848. {
  849. dt1.Rows[0][index] = "这是一段文字";
  850. }
  851. if (dr[1].ToString() == "DATE")
  852. {
  853. dt1.Rows[0][index] = DateTime.Now.ToString("yyyy-MM-dd");
  854. }
  855. if (dr[1].ToString() == "FLOAT")
  856. {
  857. dt1.Rows[0][index] = 1.0;
  858. }
  859. if (dr[1].ToString() == "CLOB")
  860. {
  861. dt1.Rows[0][index] = "一段长文字";
  862. }
  863. }
  864. return dt1;
  865. }
  866. /// <summary>
  867. /// 通过条件更新
  868. /// </summary>
  869. /// <param name="TableName"></param>
  870. /// <param name="update"></param>
  871. /// <param name="condition"></param>
  872. public string UpdateByCondition(string TableName, string update, string condition)
  873. {
  874. string sql = "update " + TableName + " set " + update + " where " + condition;
  875. command = new OracleCommand(sql, connection);
  876. LogManager.DoSQLLog(sql.ToString());
  877. Console.WriteLine(sql);
  878. Reconnect(command);
  879. try
  880. {
  881. command.ExecuteNonQuery();
  882. }
  883. catch (Exception)
  884. {
  885. command.Connection = new OracleConnection(DBConnectionString);
  886. command.Connection.Open();
  887. command.ExecuteNonQuery();
  888. }
  889. return sql;
  890. }
  891. /// <summary>
  892. /// 调用存储过程
  893. /// </summary>
  894. /// <param name="ProcedureName"></param>
  895. /// <param name="param"></param>
  896. public void CallProcedure(string ProcedureName, ref string[] param)
  897. {
  898. command = new OracleCommand(ProcedureName);
  899. command.Connection = connection;
  900. Reconnect(command);
  901. command.CommandText = ProcedureName;
  902. command.CommandType = CommandType.StoredProcedure;
  903. for (int i = 0; i < param.Length; i++)
  904. command.Parameters.Add(new OracleParameter(param[i].ToString(), OracleDbType.Varchar2, 4000, param[i], ParameterDirection.InputOutput));
  905. try
  906. {
  907. command.ExecuteNonQuery();
  908. }
  909. catch (Exception)
  910. {
  911. command.Connection = new OracleConnection(DBConnectionString);
  912. command.Connection.Open();
  913. command.ExecuteNonQuery();
  914. }
  915. for (int i = 0; i < command.Parameters.Count; i++)
  916. param[i] = command.Parameters[i].Value.ToString();
  917. }
  918. public void CallProcedure(string ProcedureName, string[] ParamName, ref string[] param)
  919. {
  920. command = new OracleCommand(ProcedureName);
  921. command.Connection = connection;
  922. Reconnect(command);
  923. command.CommandText = ProcedureName;
  924. command.CommandType = CommandType.StoredProcedure;
  925. for (int i = 0; i < param.Length; i++)
  926. {
  927. command.Parameters.Add(new OracleParameter(ParamName[i], OracleDbType.Varchar2, 200, param[i], ParameterDirection.InputOutput));
  928. //command.Parameters.Add(new OracleParameter(ParamName[i], OracleType.VarChar, 200, ParameterDirection.InputOutput, "", DataRowVersion.Default, true, param[i]));
  929. }
  930. try
  931. {
  932. command.ExecuteNonQuery();
  933. }
  934. catch (Exception)
  935. {
  936. command.Connection = new OracleConnection(ConnectionStrings);
  937. command.Connection.Open();
  938. command.ExecuteNonQuery();
  939. }
  940. for (int i = 0; i < command.Parameters.Count; i++)
  941. param[i] = command.Parameters[i].Value.ToString();
  942. }
  943. /// <summary>
  944. /// 出现异常进行回滚的执行方法
  945. /// </summary>
  946. /// <param name="SQL"></param>
  947. public void ExecuteSQLTran(params string[] SQL)
  948. {
  949. OracleTransaction tx = connection.BeginTransaction();
  950. command = new OracleCommand();
  951. command.Connection = connection;
  952. command.Transaction = tx;
  953. try
  954. {
  955. foreach (string sql in SQL)
  956. {
  957. if (!String.IsNullOrEmpty(sql))
  958. {
  959. Console.WriteLine(sql);
  960. command.CommandText = sql;
  961. try
  962. {
  963. command.ExecuteNonQuery();
  964. }
  965. catch (Exception)
  966. {
  967. command.Connection = new OracleConnection(DBConnectionString);
  968. command.Connection.Open();
  969. command.ExecuteNonQuery();
  970. }
  971. }
  972. }
  973. tx.Commit();
  974. }
  975. catch (Exception E)
  976. {
  977. tx.Rollback();
  978. throw new Exception(E.Message);
  979. }
  980. }
  981. /// <summary>
  982. /// 用于将string 的数组转换成SQL的查询内容
  983. /// </summary>
  984. /// <param name="Fields"></param>
  985. /// <returns></returns>
  986. private string AddField(string[] Fields)
  987. {
  988. string sql = " ";
  989. foreach (string field in Fields)
  990. {
  991. sql += field + ",";
  992. }
  993. return sql.Substring(0, sql.Length - 1);
  994. }
  995. /// <summary>
  996. /// 通过查询的内容获取到字段的描述
  997. /// </summary>
  998. /// <param name="field"></param>
  999. /// <returns></returns>
  1000. private static string[] GetCaptionFromField(string field)
  1001. {
  1002. string[] caption = field.Split(',');
  1003. for (int i = 0; i < caption.Length; i++)
  1004. {
  1005. caption[i] = caption[i].Substring(0, caption[i].LastIndexOf("as")).Trim();
  1006. }
  1007. return caption;
  1008. }
  1009. /// <summary>
  1010. /// 通过查询的语句获取查询的字段
  1011. /// </summary>
  1012. /// <param name="field"></param>
  1013. /// <returns></returns>
  1014. private static string[] GetField(string field)
  1015. {
  1016. string[] fields = field.Split(',');
  1017. for (int i = 0; i < fields.Length; i++)
  1018. {
  1019. fields[i] = fields[i].Substring(fields[i].LastIndexOf("as") + 2, fields[i].Length - fields[i].LastIndexOf("as") - 2).Trim();
  1020. }
  1021. return fields;
  1022. }
  1023. public object GetLabelParam(string sql)
  1024. {
  1025. DataTable dt = new DataTable();
  1026. command = new OracleCommand(sql, connection);
  1027. Reconnect(command);
  1028. OracleDataAdapter ad = new OracleDataAdapter();
  1029. ad.SelectCommand = command;
  1030. try
  1031. {
  1032. ad.Fill(dt);
  1033. }
  1034. catch (Exception)
  1035. {
  1036. connection = new OracleConnection(DBConnectionString);
  1037. connection.Open();
  1038. command = new OracleCommand(sql, connection);
  1039. ad = new OracleDataAdapter();
  1040. ad.SelectCommand = command;
  1041. ad.Fill(dt);
  1042. }
  1043. if (dt.Rows.Count > 0)
  1044. {
  1045. ad.Dispose();
  1046. return dt.Rows[0][0];
  1047. }
  1048. else
  1049. {
  1050. return "";
  1051. }
  1052. }
  1053. public static string[] GetParamFromSQL(string SQL)
  1054. {
  1055. string[] par = SQL.Split(':');
  1056. //用来存参数的数组
  1057. StringBuilder[] addpar = new StringBuilder[par.Length - 1];
  1058. string[] param = new string[par.Length - 1];
  1059. for (int i = 0; i < par.Length - 1; i++)
  1060. {
  1061. //新建一个char类型的数组用来存储每个字节的变量
  1062. char[] c = par[i + 1].ToCharArray();
  1063. addpar[i] = new StringBuilder();
  1064. for (int j = 0; j < c.Length; j++)
  1065. {
  1066. if (c[j] != ' ' && c[j] != ',' && c[j] != ')')
  1067. {
  1068. addpar[i].Append(c[j]);
  1069. }
  1070. else
  1071. {
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. for (int i = 0; i < par.Length - 1; i++)
  1077. {
  1078. param[i] = addpar[i].ToString();
  1079. }
  1080. return param;
  1081. }
  1082. public void Dispose()
  1083. {
  1084. }
  1085. private void Reconnect(OracleCommand cmd)
  1086. {
  1087. if (cmd.Connection.State == ConnectionState.Closed)
  1088. {
  1089. cmd.Connection.Open();
  1090. LogManager.DoLog("超时重连");
  1091. }
  1092. }
  1093. }
  1094. }