DataHelper.cs 43 KB

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