DataHelper.cs 44 KB

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