DataHelper.cs 38 KB

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