SqlHelper.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SQLite;
  5. namespace OTSIncAReportApp.DataOperation.DataAccess
  6. {
  7. /// <summary>
  8. /// SQLite 操作类
  9. /// </summary>
  10. public class SqlHelper
  11. {
  12. /// <summary>
  13. /// 数据库连接字符串
  14. /// </summary>
  15. public static string connectionString = "";
  16. /// <summary>
  17. /// 数据库连接定义
  18. /// </summary>
  19. private SQLiteConnection dbConnection;
  20. /// <summary>
  21. /// SQL命令定义
  22. /// </summary>
  23. private SQLiteCommand dbCommand;
  24. private SQLiteDataAdapter dataAdapter;
  25. /// <summary>
  26. /// 数据读取定义
  27. /// </summary>
  28. private SQLiteDataReader dataReader;
  29. private DataTable dt;
  30. /// <summary>
  31. /// 构造函数
  32. /// </summary>
  33. /// <param name="con">连接SQLite库字符串</param>
  34. public SqlHelper(string con)
  35. {
  36. try
  37. {
  38. dbConnection = new SQLiteConnection(con);
  39. dbConnection.Open();
  40. dbCommand = new SQLiteCommand();
  41. dbCommand.Connection = dbConnection;
  42. }
  43. catch (Exception ee)
  44. {
  45. string str = ee.ToString();
  46. }
  47. }
  48. /// <summary>
  49. /// 构造函数
  50. /// </summary>
  51. /// <param name="connectionString">连接SQLite库字符串</param>
  52. public SqlHelper()
  53. {
  54. try
  55. {
  56. dbConnection = new SQLiteConnection(connectionString);
  57. dbConnection.Open();
  58. dbCommand = new SQLiteCommand();
  59. dbCommand.Connection = dbConnection;
  60. }
  61. catch (Exception)
  62. {
  63. }
  64. }
  65. /// <summary>
  66. /// 创建一个指定名字的数据库
  67. /// </summary>
  68. /// <param name="basename"></param>
  69. public static void CreateNewDatabase(string basename)
  70. {
  71. try
  72. {
  73. SQLiteConnection.CreateFile(basename);
  74. }
  75. catch (Exception)
  76. {
  77. }
  78. }
  79. /// <summary>
  80. /// 删除指定的数据库文件
  81. /// </summary>
  82. /// <param name="basename"></param>
  83. public void DeleteDataBase(string basename)
  84. {
  85. try
  86. {
  87. if (System.IO.File.Exists(basename))
  88. {
  89. System.IO.File.Delete(basename);
  90. }
  91. }
  92. catch (Exception)
  93. {
  94. }
  95. }
  96. /// <summary>
  97. /// 执行SQL命令
  98. /// </summary>
  99. /// <returns>The query.</returns>
  100. /// <param name="queryString">SQL命令字符串</param>
  101. public DataTable ExecuteQuery(string queryString)
  102. {
  103. try
  104. {
  105. dataAdapter = new SQLiteDataAdapter(queryString, dbConnection);
  106. DataSet ds = new DataSet();
  107. dataAdapter.Fill(ds);
  108. dt = ds.Tables[0];
  109. }
  110. catch (Exception)
  111. {
  112. }
  113. return dt;
  114. }
  115. public DataTable ExecuteQuery2(string queryString)
  116. {
  117. SQLiteCommand sqlCommand = new SQLiteCommand(queryString,dbConnection);
  118. try
  119. {
  120. SQLiteDataReader reader = sqlCommand.ExecuteReader();
  121. dt = new DataTable();
  122. dt.Load(reader);
  123. }
  124. catch (Exception ee)
  125. {
  126. }
  127. return dt;
  128. }
  129. /// <summary>
  130. /// 关闭数据库连接
  131. /// </summary>
  132. public void CloseConnection()
  133. {
  134. //销毁Commend
  135. if (dbCommand != null)
  136. {
  137. dbCommand.Cancel();
  138. }
  139. dbCommand = null;
  140. //销毁Reader
  141. if (dataReader != null)
  142. {
  143. dataReader.Close();
  144. }
  145. dataReader = null;
  146. //销毁Connection
  147. if (dbConnection != null)
  148. {
  149. dbConnection.Close();
  150. }
  151. dbConnection = null;
  152. }
  153. /// <summary>
  154. /// 读取整张数据表
  155. /// </summary>
  156. /// <returns>The full table.</returns>
  157. /// <param name="tableName">数据表名称</param>
  158. public DataTable ReadFullTable(string tableName)
  159. {
  160. string queryString = "SELECT * FROM " + tableName;
  161. return ExecuteQuery(queryString);
  162. }
  163. /// <summary>
  164. /// /// 执行一个查询语句,返回一个包含查询结果的DataTable
  165. /// /// </summary>
  166. /// /// <param name="sql">要执行的查询语句</param>
  167. /// /// <param name="parameters">执行查询语句的参数</param>
  168. /// /// <returns></returns>
  169. public DataTable ExecuteDataTable(string sql, params SQLiteParameter[] parameters)
  170. {
  171. using (SQLiteCommand command = new SQLiteCommand(sql, dbConnection))
  172. {
  173. if (parameters != null)
  174. {
  175. command.Parameters.AddRange(parameters);
  176. }
  177. SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
  178. DataTable data = new DataTable();
  179. adapter.Fill(data);
  180. return data;
  181. }
  182. }
  183. /// <summary>
  184. /// /// tbale转list
  185. /// /// </summary>
  186. /// /// <typeparam name="T"></typeparam>
  187. /// /// <returns></returns>
  188. public List<T> TableToList<T>(DataTable table) where T : class, new()
  189. {
  190. var result = new List<T>();
  191. var propertys = typeof(T).GetProperties();
  192. foreach (DataRow dr in table.Rows)
  193. {
  194. var item = new T();
  195. result.Add(item);
  196. foreach (var pi in propertys)
  197. {
  198. if (!table.Columns.Contains(pi.Name))
  199. continue;
  200. var value = dr[pi.Name];
  201. if (value is DBNull || value == null)
  202. continue;
  203. if (value.GetType().ToString() == "System.Int64")
  204. {
  205. pi.SetValue(item, Convert.ToInt32(value));
  206. }
  207. else if(value.GetType().ToString() == "System.Decimal")
  208. {
  209. pi.SetValue(item, Convert.ToDouble(value));
  210. }
  211. else
  212. {
  213. pi.SetValue(item, value);
  214. }
  215. }
  216. }
  217. return result;
  218. }
  219. /// <summary>
  220. /// /// tbale转list
  221. /// /// </summary>
  222. /// /// <typeparam name="T"></typeparam>
  223. /// /// <returns></returns>
  224. public List<T> RowsToList<T>(DataRow[] table) where T : class, new()
  225. {
  226. var result = new List<T>();
  227. var propertys = typeof(T).GetProperties();
  228. foreach (DataRow dr in table)
  229. {
  230. var item = new T();
  231. result.Add(item);
  232. foreach (var pi in propertys)
  233. {
  234. if (!dr.Table.Columns.Contains(pi.Name))
  235. continue;
  236. var value = dr[pi.Name];
  237. if (value is DBNull || value == null)
  238. continue;
  239. if (value.GetType().ToString() == "System.Int64")
  240. {
  241. pi.SetValue(item, Convert.ToInt32(value));
  242. }
  243. else
  244. {
  245. pi.SetValue(item, value);
  246. }
  247. }
  248. }
  249. return result;
  250. }
  251. /// <summary>
  252. /// 向指定数据表中插入数据
  253. /// </summary>
  254. /// <returns>The values.</returns>
  255. /// <param name="tableName">数据表名称</param>
  256. /// <param name="values">插入的数值</param>
  257. public DataTable InsertValues(string tableName, string[] values)
  258. {
  259. //获取数据表中字段数目
  260. int fieldCount = ReadFullTable(tableName).Columns.Count;
  261. //当插入的数据长度不等于字段数目时引发异常
  262. if (values.Length != fieldCount)
  263. {
  264. throw new SQLiteException("values.Length!=fieldCount");
  265. }
  266. string queryString = "INSERT INTO " + tableName + " VALUES (" + "'" + values[0] + "'";
  267. for (int i = 1; i < values.Length; i++)
  268. {
  269. queryString += ", " + "'" + values[i] + "'";
  270. }
  271. queryString += " )";
  272. return ExecuteQuery(queryString);
  273. }
  274. /// <summary>
  275. /// 更新指定数据表内的数据
  276. /// </summary>
  277. /// <returns>The values.</returns>
  278. /// <param name="tableName">数据表名称</param>
  279. /// <param name="colNames">字段名</param>
  280. /// <param name="colValues">字段名对应的数据</param>
  281. /// <param name="key">关键字</param>
  282. /// <param name="value">关键字对应的值</param>
  283. /// <param name="operation">运算符:=,<,>,...,默认“=”</param>
  284. public DataTable UpdateValues(string tableName, string[] colNames, string[] colValues, string key, string value, string operation = "=")
  285. {
  286. //当字段名称和字段数值不对应时引发异常
  287. if (colNames.Length != colValues.Length)
  288. {
  289. throw new SQLiteException("colNames.Length!=colValues.Length");
  290. }
  291. string queryString = "UPDATE " + tableName + " SET " + colNames[0] + "=" + "'" + colValues[0] + "'";
  292. for (int i = 1; i < colValues.Length; i++)
  293. {
  294. queryString += ", " + colNames[i] + "=" + "'" + colValues[i] + "'";
  295. }
  296. queryString += " WHERE " + key + operation + "'" + value + "'";
  297. return ExecuteQuery(queryString);
  298. }
  299. /// <summary>
  300. /// 删除指定数据表内的数据
  301. /// </summary>
  302. /// <returns>The values.</returns>
  303. /// <param name="tableName">数据表名称</param>
  304. /// <param name="colNames">字段名</param>
  305. /// <param name="colValues">字段名对应的数据</param>
  306. public DataTable DeleteValuesOR(string tableName, string[] colNames, string[] colValues, string[] operations)
  307. {
  308. //当字段名称和字段数值不对应时引发异常
  309. if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
  310. {
  311. throw new SQLiteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
  312. }
  313. string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
  314. for (int i = 1; i < colValues.Length; i++)
  315. {
  316. queryString += "OR " + colNames[i] + operations[0] + "'" + colValues[i] + "'";
  317. }
  318. return ExecuteQuery(queryString);
  319. }
  320. /// <summary>
  321. /// 删除指定数据表内的数据
  322. /// </summary>
  323. /// <returns>The values.</returns>
  324. /// <param name="tableName">数据表名称</param>
  325. /// <param name="colNames">字段名</param>
  326. /// <param name="colValues">字段名对应的数据</param>
  327. public DataTable DeleteValuesAND(string tableName, string[] colNames, string[] colValues, string[] operations)
  328. {
  329. //当字段名称和字段数值不对应时引发异常
  330. if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
  331. {
  332. throw new SQLiteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
  333. }
  334. string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
  335. for (int i = 1; i < colValues.Length; i++)
  336. {
  337. queryString += " AND " + colNames[i] + operations[i] + "'" + colValues[i] + "'";
  338. }
  339. return ExecuteQuery(queryString);
  340. }
  341. /// <summary>
  342. /// 创建数据表
  343. /// </summary> +
  344. /// <returns>The table.</returns>
  345. /// <param name="tableName">数据表名</param>
  346. /// <param name="colNames">字段名</param>
  347. /// <param name="colTypes">字段名类型</param>
  348. public DataTable CreateTable(string tableName, string[] colNames, string[] colTypes)
  349. {
  350. string queryString = "CREATE TABLE IF NOT EXISTS " + tableName + "( " + colNames[0] + " " + colTypes[0];
  351. for (int i = 1; i < colNames.Length; i++)
  352. {
  353. queryString += ", " + colNames[i] + " " + colTypes[i];
  354. }
  355. queryString += " ) ";
  356. return ExecuteQuery(queryString);
  357. }
  358. /// <summary>
  359. /// 删除数据库表
  360. /// </summary>
  361. /// <param name="tableName"></param>
  362. /// <returns></returns>
  363. public DataTable DeleteTable(string tableName)
  364. {
  365. string queryString = "drop table " + tableName;
  366. return ExecuteQuery(queryString);
  367. }
  368. /// <summary>
  369. /// Reads the table.
  370. /// </summary>
  371. /// <returns>The table.</returns>
  372. /// <param name="tableName">Table name.</param>
  373. /// <param name="items">Items.</param>
  374. /// <param name="colNames">Col names.</param>
  375. /// <param name="operations">Operations.</param>
  376. /// <param name="colValues">Col values.</param>
  377. public DataTable ReadTable(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues)
  378. {
  379. string queryString = "SELECT " + items[0];
  380. for (int i = 1; i < items.Length; i++)
  381. {
  382. queryString += ", " + items[i];
  383. }
  384. queryString += " FROM " + tableName + " where 1=1";
  385. for (int i = 0; i < colNames.Length; i++)
  386. {
  387. queryString += " AND " + colNames[i] + " " + operations[i] + " " + colValues[0] + " ";
  388. }
  389. return ExecuteQuery(queryString);
  390. }
  391. public int ExecuteQueryResult(string queryString)
  392. {
  393. int result = -1;
  394. try
  395. {
  396. dbCommand.CommandText = queryString;
  397. result = dbCommand.ExecuteNonQuery();
  398. }
  399. catch (Exception e)
  400. {
  401. }
  402. return result;
  403. }
  404. public int ExecuteQueryResult(string queryString, SQLiteTransaction tr)
  405. {
  406. int result = -1;
  407. try
  408. {
  409. dbCommand.CommandText = queryString;
  410. dbCommand.Transaction = tr;
  411. result = dbCommand.ExecuteNonQuery();
  412. }
  413. catch (Exception e)
  414. {
  415. }
  416. return result;
  417. }
  418. /// <summary>
  419. /// 执行SQL命令,并带有一个BLOB字段对象的参数输入
  420. /// </summary>
  421. /// <param name="queryString"></param>
  422. /// <param name="parmstr"></param>
  423. /// <param name="in_b"></param>
  424. /// <returns></returns>
  425. public int ExecuteQuery(string queryString, string parmstr, byte[] in_b)
  426. {
  427. int iresult = -1;
  428. try
  429. {
  430. dbCommand.CommandText = queryString;
  431. dbCommand.Parameters.Add(parmstr, System.Data.DbType.Binary).Value = in_b;
  432. iresult = dbCommand.ExecuteNonQuery();
  433. }
  434. catch (Exception e)
  435. {
  436. }
  437. return iresult;
  438. }
  439. /// <summary>
  440. /// 执行SQL命令,并带有一个BLOB字段对象的参数输入
  441. /// </summary>
  442. /// <param name="queryString"></param>
  443. /// <param name="parmstr"></param>
  444. /// <param name="in_b"></param>
  445. /// <returns></returns>
  446. public int ExecuteQuery(string queryString, string parmstr, byte[] in_b, SQLiteTransaction tr)
  447. {
  448. int iresult = -1;
  449. try
  450. {
  451. dbCommand.CommandText = queryString;
  452. dbCommand.Transaction = tr;
  453. dbCommand.Parameters.Add(parmstr, System.Data.DbType.Binary).Value = in_b;
  454. //or
  455. iresult = dbCommand.ExecuteNonQuery();
  456. }
  457. catch (Exception e)
  458. {
  459. }
  460. return iresult;
  461. }
  462. /// <summary>
  463. /// 执行SQL命令,并带有两个BLOB字段对象的参数输入
  464. /// </summary>
  465. /// <param name="queryString"></param>
  466. /// <param name="parmstr"></param>
  467. /// <param name="in_b"></param>
  468. /// <param name="in_b2"></param>
  469. /// <returns></returns>
  470. public int ExecuteQuery(string queryString, string parmstr, byte[] in_b, string parmstr2, byte[] in_b2)
  471. {
  472. int iresult = -1;
  473. try
  474. {
  475. dbCommand.CommandText = queryString;
  476. dbCommand.Parameters.Add(parmstr, System.Data.DbType.Binary).Value = in_b;
  477. dbCommand.Parameters.Add(parmstr2, System.Data.DbType.Binary).Value = in_b2;
  478. iresult = dbCommand.ExecuteNonQuery();
  479. }
  480. catch (Exception e)
  481. {
  482. }
  483. return iresult;
  484. }
  485. /// <summary>
  486. /// 执行SQL命令,并带有两个BLOB字段对象的参数输入
  487. /// </summary>
  488. /// <param name="queryString"></param>
  489. /// <param name="parmstr"></param>
  490. /// <param name="in_b"></param>
  491. /// <param name="in_b2"></param>
  492. /// <returns></returns>
  493. public int ExecuteQuery(string queryString, string parmstr, byte[] in_b, string parmstr2, byte[] in_b2, SQLiteTransaction tr)
  494. {
  495. int iresult = -1;
  496. try
  497. {
  498. dbCommand.CommandText = queryString;
  499. dbCommand.Transaction = tr;
  500. dbCommand.Parameters.Add(parmstr, System.Data.DbType.Binary).Value = in_b;
  501. dbCommand.Parameters.Add(parmstr2, System.Data.DbType.Binary).Value = in_b2;
  502. iresult = dbCommand.ExecuteNonQuery();
  503. }
  504. catch (Exception e)
  505. {
  506. }
  507. return iresult;
  508. }
  509. /// <summary>
  510. /// 执行SQL命令,并带有三个BLOB字段对象的参数输入
  511. /// </summary>
  512. /// <param name="queryString"></param>
  513. /// <param name="parmstr"></param>
  514. /// <param name="in_b"></param>
  515. /// <param name="in_b2"></param>
  516. /// <returns></returns>
  517. public int ExecuteQuery(string queryString, string parmstr, byte[] in_b, string parmstr2, byte[] in_b2, string parmstr3, byte[] in_b3)
  518. {
  519. int iresult = -1;
  520. try
  521. {
  522. dbCommand.CommandText = queryString;
  523. dbCommand.Parameters.Add(parmstr, System.Data.DbType.Binary).Value = in_b;
  524. dbCommand.Parameters.Add(parmstr2, System.Data.DbType.Binary).Value = in_b2;
  525. dbCommand.Parameters.Add(parmstr3, System.Data.DbType.Binary).Value = in_b3;
  526. iresult = dbCommand.ExecuteNonQuery();
  527. }
  528. catch (Exception e)
  529. {
  530. }
  531. return iresult;
  532. }
  533. /// <summary>
  534. /// 执行SQL命令,并带有三个BLOB字段对象的参数输入
  535. /// </summary>
  536. /// <param name="queryString"></param>
  537. /// <param name="parmstr"></param>
  538. /// <param name="in_b"></param>
  539. /// <param name="in_b2"></param>
  540. /// <returns></returns>
  541. public int ExecuteQuery(string queryString, string parmstr, byte[] in_b, string parmstr2, byte[] in_b2, string parmstr3, byte[] in_b3, SQLiteTransaction tr)
  542. {
  543. int iresult = -1;
  544. try
  545. {
  546. dbCommand.CommandText = queryString;
  547. dbCommand.Transaction = tr;
  548. dbCommand.Parameters.Add(parmstr, System.Data.DbType.Binary).Value = in_b;
  549. dbCommand.Parameters.Add(parmstr2, System.Data.DbType.Binary).Value = in_b2;
  550. dbCommand.Parameters.Add(parmstr3, System.Data.DbType.Binary).Value = in_b3;
  551. iresult = dbCommand.ExecuteNonQuery();
  552. }
  553. catch (Exception e)
  554. {
  555. }
  556. return iresult;
  557. }
  558. /// <summary>
  559. /// 开始事务
  560. /// </summary>
  561. /// <returns></returns>
  562. public SQLiteTransaction BeginTranscation()
  563. {
  564. return dbConnection.BeginTransaction();
  565. }
  566. /// <summary>
  567. /// 提交事务
  568. /// </summary>
  569. /// <param name="tx"></param>
  570. public void TranscationCommit(SQLiteTransaction tr)
  571. {
  572. tr.Commit();
  573. }
  574. /// <summary>
  575. /// 回滚事务
  576. /// </summary>
  577. /// <param name="tx"></param>
  578. public void TranscationRollback(SQLiteTransaction tr)
  579. {
  580. tr.Rollback();
  581. }
  582. }
  583. }