DataHelper.cs 43 KB

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