DataHelper.cs 42 KB

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