DataHelper.cs 46 KB

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