DataHelper.cs 44 KB

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