当前位置:   article > 正文

C# 操作SQLite 增、删、改、查、创建_c# sqlite

c# sqlite

一、简介

SQLite是一个轻量级、跨平台的关系型数据库,在小型项目中,方便,易用,同时支持多种开发语言,下面是我用C#语言对SQLite 的一个封装。

Winfrom界面如下:

二、代码部分

1.SQLiteHelper.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.Common;
  5. using System.Data.SQLite;
  6. using System.IO;
  7. using System.Text;
  8. namespace MySQLiteHelper
  9. {
  10. public class SQLiteHelper
  11. {
  12. #region 字段
  13. /// <summary>
  14. /// 事务的基类
  15. /// </summary>
  16. private DbTransaction DBtrans;
  17. /// <summary>
  18. /// 使用静态变量字典解决多线程实例本类,实现一个数据库对应一个clslock
  19. /// </summary>
  20. private static readonly Dictionary<string, ClsLock> RWL = new Dictionary<string, ClsLock>();
  21. /// <summary>
  22. /// 数据库地址
  23. /// </summary>
  24. private readonly string mdataFile;
  25. /// <summary>
  26. /// 数据库密码
  27. /// </summary>
  28. private readonly string mPassWord;
  29. private readonly string LockName = null;
  30. /// <summary>
  31. /// 数据库连接定义
  32. /// </summary>
  33. private SQLiteConnection mConn;
  34. #endregion
  35. #region 构造函数
  36. /// <summary>
  37. /// 根据数据库地址初始化
  38. /// </summary>
  39. /// <param name="dataFile">数据库地址</param>
  40. public SQLiteHelper(string dataFile)
  41. {
  42. this.mdataFile = dataFile ?? throw new ArgumentNullException("dataFile=null");
  43. //this.mdataFile = AppDomain.CurrentDomain.BaseDirectory + dataFile;
  44. this.mdataFile = dataFile;
  45. if (!RWL.ContainsKey(dataFile))
  46. {
  47. LockName = dataFile;
  48. RWL.Add(dataFile, new ClsLock());
  49. }
  50. }
  51. /// <summary>
  52. /// 使用密码打开数据库
  53. /// </summary>
  54. /// <param name="dataFile">数据库地址</param>
  55. /// <param name="PassWord">数据库密码</param>
  56. public SQLiteHelper(string dataFile, string PassWord)
  57. {
  58. this.mdataFile = dataFile ?? throw new ArgumentNullException("dataFile is null");
  59. this.mPassWord = PassWord ?? throw new ArgumentNullException("PassWord is null");
  60. //this.mdataFile = AppDomain.CurrentDomain.BaseDirectory + dataFile;
  61. this.mdataFile = dataFile;
  62. if (!RWL.ContainsKey(dataFile))
  63. {
  64. LockName = dataFile;
  65. RWL.Add(dataFile, new ClsLock());
  66. }
  67. }
  68. #endregion
  69. #region 打开/关闭 数据库
  70. /// <summary>
  71. /// 打开 SQLiteManager 使用的数据库连接
  72. /// </summary>
  73. public void Open()
  74. {
  75. if (string.IsNullOrWhiteSpace(mPassWord))
  76. {
  77. mConn = OpenConnection(this.mdataFile);
  78. }
  79. else
  80. {
  81. mConn = OpenConnection(this.mdataFile, mPassWord);
  82. }
  83. Console.WriteLine("打开数据库成功");
  84. }
  85. /// <summary>
  86. /// 关闭连接
  87. /// </summary>
  88. public void Close()
  89. {
  90. if (this.mConn != null)
  91. {
  92. try
  93. {
  94. this.mConn.Close();
  95. if (RWL.ContainsKey(LockName))
  96. {
  97. RWL.Remove(LockName);
  98. }
  99. }
  100. catch
  101. {
  102. Console.WriteLine("关闭失败");
  103. }
  104. }
  105. Console.WriteLine("关闭数据库成功");
  106. }
  107. #endregion
  108. #region 事务
  109. /// <summary>
  110. /// 开始事务
  111. /// </summary>
  112. public void BeginTrain()
  113. {
  114. EnsureConnection();
  115. DBtrans = mConn.BeginTransaction();
  116. }
  117. /// <summary>
  118. /// 提交事务
  119. /// </summary>
  120. public void DBCommit()
  121. {
  122. try
  123. {
  124. DBtrans.Commit();
  125. }
  126. catch (Exception)
  127. {
  128. DBtrans.Rollback();
  129. }
  130. }
  131. #endregion
  132. #region 工具
  133. /// <summary>
  134. /// 打开一个SQLite数据库文件,如果文件不存在,则创建(无密码)
  135. /// </summary>
  136. /// <param name="dataFile"></param>
  137. /// <returns>SQLiteConnection 类</returns>
  138. private SQLiteConnection OpenConnection(string dataFile)
  139. {
  140. if (dataFile == null)
  141. {
  142. throw new ArgumentNullException("dataFiledataFile=null");
  143. }
  144. if (!File.Exists(dataFile))
  145. {
  146. SQLiteConnection.CreateFile(dataFile);
  147. }
  148. SQLiteConnection conn = new SQLiteConnection();
  149. SQLiteConnectionStringBuilder conStr = new SQLiteConnectionStringBuilder
  150. {
  151. DataSource = dataFile
  152. };
  153. conn.ConnectionString = conStr.ToString();
  154. conn.Open();
  155. return conn;
  156. }
  157. /// <summary>
  158. /// 打开一个SQLite数据库文件,如果文件不存在,则创建(有密码)
  159. /// </summary>
  160. /// <param name="dataFile"></param>
  161. /// <param name="Password"></param>
  162. /// <returns>SQLiteConnection 类</returns>
  163. private SQLiteConnection OpenConnection(string dataFile, string Password)
  164. {
  165. if (dataFile == null)
  166. {
  167. throw new ArgumentNullException("dataFile=null");
  168. }
  169. if (!File.Exists(Convert.ToString(dataFile)))
  170. {
  171. SQLiteConnection.CreateFile(dataFile);
  172. }
  173. try
  174. {
  175. SQLiteConnection conn = new SQLiteConnection();
  176. SQLiteConnectionStringBuilder conStr = new SQLiteConnectionStringBuilder
  177. {
  178. DataSource = dataFile,
  179. Password = Password
  180. };
  181. conn.ConnectionString = conStr.ToString();
  182. conn.Open();
  183. return conn;
  184. }
  185. catch (Exception)
  186. {
  187. return null;
  188. }
  189. }
  190. /// <summary>
  191. /// 读取 或 设置 SQLiteManager 使用的数据库连接
  192. /// </summary>
  193. public SQLiteConnection Connection
  194. {
  195. get
  196. {
  197. return mConn;
  198. }
  199. private set
  200. {
  201. mConn = value ?? throw new ArgumentNullException();
  202. }
  203. }
  204. /// <summary>
  205. /// 确保数据库是连接状态
  206. /// </summary>
  207. /// <exception cref="Exception"></exception>
  208. protected void EnsureConnection()
  209. {
  210. if (this.mConn == null)
  211. {
  212. throw new Exception("SQLiteManager.Connection=null");
  213. }
  214. if (mConn.State != ConnectionState.Open)
  215. {
  216. mConn.Open();
  217. }
  218. }
  219. /// <summary>
  220. /// 获取数据库文件的路径
  221. /// </summary>
  222. /// <returns></returns>
  223. public string GetDataFile()
  224. {
  225. return this.mdataFile;
  226. }
  227. /// <summary>
  228. /// 判断表 table 是否存在
  229. /// </summary>
  230. /// <param name="table"></param>
  231. /// <returns>存在返回true,否则返回false</returns>
  232. public bool TableExists(string table)
  233. {
  234. if (table == null)
  235. {
  236. throw new ArgumentNullException("table=null");
  237. }
  238. EnsureConnection();
  239. SQLiteDataReader reader = ExecuteReader("SELECT count(*) as c FROM sqlite_master WHERE type='table' AND name=@tableName ", new SQLiteParameter[] { new SQLiteParameter("tableName", table) });
  240. if (reader == null)
  241. {
  242. return false;
  243. }
  244. reader.Read();
  245. int c = reader.GetInt32(0);
  246. reader.Close();
  247. reader.Dispose();
  248. //return false;
  249. return c == 1;
  250. }
  251. /// <summary>
  252. /// VACUUM 命令(通过复制主数据库中的内容到一个临时数据库文件,然后清空主数据库,并从副本中重新载入原始的数据库文件)
  253. /// </summary>
  254. /// <returns></returns>
  255. public bool Vacuum()
  256. {
  257. try
  258. {
  259. using (SQLiteCommand Command = new SQLiteCommand("VACUUM", Connection))
  260. {
  261. Command.ExecuteNonQuery();
  262. }
  263. return true;
  264. }
  265. catch (System.Data.SQLite.SQLiteException)
  266. {
  267. return false;
  268. }
  269. }
  270. #endregion
  271. #region 执行SQL
  272. /// <summary>
  273. /// 执行SQL, 并返回 SQLiteDataReader 对象结果
  274. /// </summary>
  275. /// <param name="sql"></param>
  276. /// <param name="paramArr">null 表示无参数</param>
  277. /// <returns></returns>
  278. public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] paramArr)
  279. {
  280. if (sql == null)
  281. {
  282. throw new ArgumentNullException("sql=null");
  283. }
  284. EnsureConnection();
  285. using (RWL[LockName].Read())
  286. {
  287. using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection))
  288. {
  289. if (paramArr != null)
  290. {
  291. cmd.Parameters.AddRange(paramArr);
  292. }
  293. try
  294. {
  295. SQLiteDataReader reader = cmd.ExecuteReader();
  296. cmd.Parameters.Clear();
  297. return reader;
  298. }
  299. catch (Exception)
  300. {
  301. return null;
  302. }
  303. }
  304. }
  305. }
  306. /// <summary>
  307. /// 执行查询,并返回dataset对象
  308. /// </summary>
  309. /// <param name="sql">SQL查询语句</param>
  310. /// <param name="paramArr">参数数组</param>
  311. /// <returns></returns>
  312. public DataSet ExecuteDataSet(string sql, SQLiteParameter[] paramArr)
  313. {
  314. if (sql == null)
  315. {
  316. throw new ArgumentNullException("sql=null");
  317. }
  318. this.EnsureConnection();
  319. using (RWL[LockName].Read())
  320. {
  321. using (SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection))
  322. {
  323. if (paramArr != null)
  324. {
  325. cmd.Parameters.AddRange(paramArr);
  326. }
  327. try
  328. {
  329. SQLiteDataAdapter da = new SQLiteDataAdapter();
  330. DataSet ds = new DataSet();
  331. da.SelectCommand = cmd;
  332. da.Fill(ds);
  333. cmd.Parameters.Clear();
  334. da.Dispose();
  335. return ds;
  336. }
  337. catch (Exception)
  338. {
  339. return null;
  340. }
  341. }
  342. }
  343. }
  344. /// <summary>
  345. /// 执行SQL查询,并返回dataset对象。
  346. /// </summary>
  347. /// <param name="strTable">映射源表的名称</param>
  348. /// <param name="sql">SQL语句</param>
  349. /// <param name="paramArr">SQL参数数组</param>
  350. /// <returns></returns>
  351. public DataSet ExecuteDataSet(string strTable, string sql, SQLiteParameter[] paramArr)
  352. {
  353. if (sql == null)
  354. {
  355. throw new ArgumentNullException("sql=null");
  356. }
  357. this.EnsureConnection();
  358. using (RWL[LockName].Read())
  359. {
  360. using (SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection))
  361. {
  362. if (paramArr != null)
  363. {
  364. cmd.Parameters.AddRange(paramArr);
  365. }
  366. try
  367. {
  368. SQLiteDataAdapter da = new SQLiteDataAdapter();
  369. DataSet ds = new DataSet();
  370. da.SelectCommand = cmd;
  371. da.Fill(ds, strTable);
  372. cmd.Parameters.Clear();
  373. da.Dispose();
  374. return ds;
  375. }
  376. catch (Exception)
  377. {
  378. return null;
  379. }
  380. }
  381. }
  382. }
  383. /// <summary>
  384. /// 执行SQL,返回受影响的行数,可用于执行表创建语句,paramArr == null 表示无参数
  385. /// </summary>
  386. /// <param name="sql"></param>
  387. /// <returns></returns>
  388. public int ExecuteNonQuery(string sql, SQLiteParameter[] paramArr)
  389. {
  390. if (sql == null)
  391. {
  392. throw new ArgumentNullException("sql=null");
  393. }
  394. this.EnsureConnection();
  395. using (RWL[LockName].Read())
  396. {
  397. try
  398. {
  399. using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection))
  400. {
  401. if (paramArr != null)
  402. {
  403. foreach (SQLiteParameter p in paramArr)
  404. {
  405. cmd.Parameters.Add(p);
  406. }
  407. }
  408. int c = cmd.ExecuteNonQuery();
  409. cmd.Parameters.Clear();
  410. return c;
  411. }
  412. }
  413. catch (SQLiteException)
  414. {
  415. return 0;
  416. }
  417. }
  418. }
  419. /// <summary>
  420. /// 执行SQL,返回结果集第一行,如果结果集为空,那么返回空 List(List.Count=0),
  421. /// rowWrapper = null 时,使用 WrapRowToDictionary
  422. /// </summary>
  423. /// <param name="sql"></param>
  424. /// <param name="paramArr"></param>
  425. /// <returns></returns>
  426. public object ExecuteScalar(string sql, SQLiteParameter[] paramArr)
  427. {
  428. if (sql == null)
  429. {
  430. throw new ArgumentNullException("sql=null");
  431. }
  432. this.EnsureConnection();
  433. using (RWL[LockName].Read())
  434. {
  435. using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection))
  436. {
  437. if (paramArr != null)
  438. {
  439. cmd.Parameters.AddRange(paramArr);
  440. }
  441. try
  442. {
  443. object reader = cmd.ExecuteScalar();
  444. cmd.Parameters.Clear();
  445. cmd.Dispose();
  446. return reader;
  447. }
  448. catch (Exception)
  449. {
  450. return null;
  451. }
  452. }
  453. }
  454. }
  455. /// <summary>
  456. /// 查询一行记录,无结果时返回 null,conditionCol = null 时将忽略条件,直接执行 select * from table
  457. /// </summary>
  458. /// <param name="table">表名</param>
  459. /// <param name="conditionCol"></param>
  460. /// <param name="conditionVal"></param>
  461. /// <returns></returns>
  462. public object QueryOne(string table, string conditionCol, object conditionVal)
  463. {
  464. if (table == null)
  465. {
  466. throw new ArgumentNullException("table=null");
  467. }
  468. this.EnsureConnection();
  469. string sql = "select * from " + table;
  470. if (conditionCol != null)
  471. {
  472. sql += " where " + conditionCol + "=@" + conditionCol;
  473. }
  474. object result = ExecuteScalar(sql, new SQLiteParameter[] { new SQLiteParameter(conditionCol, conditionVal) });
  475. return result;
  476. }
  477. #endregion
  478. #region 增 删 改
  479. /// <summary>
  480. /// 执行 insert into 语句
  481. /// </summary>
  482. /// <param name="table"></param>
  483. /// <param name="entity"></param>
  484. /// <returns></returns>
  485. public int InsertData(string table, Dictionary<string, object> entity)
  486. {
  487. if (table == null)
  488. {
  489. throw new ArgumentNullException("table=null");
  490. }
  491. this.EnsureConnection();
  492. string sql = BuildInsert(table, entity);
  493. return this.ExecuteNonQuery(sql, BuildParamArray(entity));
  494. }
  495. /// <summary>
  496. /// 执行 update 语句,注意:如果 where = null,那么 whereParams 也为 null,
  497. /// </summary>
  498. /// <param name="table">表名</param>
  499. /// <param name="entity">要修改的列名和列名的值</param>
  500. /// <param name="where">查找符合条件的列</param>
  501. /// <param name="whereParams">where条件中参数的值</param>
  502. /// <returns></returns>
  503. public int Update(string table, Dictionary<string, object> entity, string where, SQLiteParameter[] whereParams)
  504. {
  505. if (table == null)
  506. {
  507. throw new ArgumentNullException("table=null");
  508. }
  509. this.EnsureConnection();
  510. string sql = BuildUpdate(table, entity);
  511. SQLiteParameter[] parameter = BuildParamArray(entity);
  512. if (where != null)
  513. {
  514. sql += " where " + where;
  515. if (whereParams != null)
  516. {
  517. SQLiteParameter[] newArr = new SQLiteParameter[(parameter.Length + whereParams.Length)];
  518. Array.Copy(parameter, newArr, parameter.Length);
  519. Array.Copy(whereParams, 0, newArr, parameter.Length, whereParams.Length);
  520. parameter = newArr;
  521. }
  522. }
  523. return this.ExecuteNonQuery(sql, parameter);
  524. }
  525. /// <summary>
  526. /// 执行 delete from table 语句,where不必包含'where'关键字,where = null 时将忽略 whereParams
  527. /// </summary>
  528. /// <param name="table"></param>
  529. /// <param name="where"></param>
  530. /// <param name="whereParams"></param>
  531. /// <returns></returns>
  532. public int Delete(string table, string where, SQLiteParameter[] whereParams)
  533. {
  534. if (table == null)
  535. {
  536. throw new ArgumentNullException("table=null");
  537. }
  538. this.EnsureConnection();
  539. string sql = "delete from " + table + " ";
  540. if (where != null)
  541. {
  542. sql += "where " + where;
  543. }
  544. return ExecuteNonQuery(sql, whereParams);
  545. }
  546. /// <summary>
  547. /// 将 Dictionary 类型数据 转换为 SQLiteParameter[] 类型
  548. /// </summary>
  549. /// <param name="entity"></param>
  550. /// <returns></returns>
  551. private SQLiteParameter[] BuildParamArray(Dictionary<string, object> entity)
  552. {
  553. List<SQLiteParameter> list = new List<SQLiteParameter>();
  554. foreach (string key in entity.Keys)
  555. {
  556. list.Add(new SQLiteParameter(key, entity[key]));
  557. }
  558. if (list.Count == 0)
  559. {
  560. return null;
  561. }
  562. return list.ToArray();
  563. }
  564. /// <summary>
  565. /// 将 Dictionary 类型数据 转换为 插入数据 的 SQL语句
  566. /// </summary>
  567. /// <param name="table">表名</param>
  568. /// <param name="entity">字典</param>
  569. /// <returns></returns>
  570. private string BuildInsert(string table, Dictionary<string, object> entity)
  571. {
  572. StringBuilder buf = new StringBuilder();
  573. buf.Append("insert into ").Append(table);
  574. buf.Append(" (");
  575. foreach (string key in entity.Keys)
  576. {
  577. buf.Append(key).Append(",");
  578. }
  579. buf.Remove(buf.Length - 1, 1); // 移除最后一个,
  580. buf.Append(") ");
  581. buf.Append("values(");
  582. foreach (string key in entity.Keys)
  583. {
  584. buf.Append("@").Append(key).Append(","); // 创建一个参数
  585. }
  586. buf.Remove(buf.Length - 1, 1);
  587. buf.Append(") ");
  588. return buf.ToString();
  589. }
  590. /// <summary>
  591. /// 将 Dictionary 类型数据 转换为 修改数据 的 SQL语句
  592. /// </summary>
  593. /// <param name="table">表名</param>
  594. /// <param name="entity">字典</param>
  595. /// <returns></returns>
  596. private string BuildUpdate(string table, Dictionary<string, object> entity)
  597. {
  598. StringBuilder buf = new StringBuilder();
  599. buf.Append("update ").Append(table).Append(" set ");
  600. foreach (string key in entity.Keys)
  601. {
  602. buf.Append(key).Append("=").Append("@").Append(key).Append(",");
  603. }
  604. buf.Remove(buf.Length - 1, 1);
  605. buf.Append(" ");
  606. return buf.ToString();
  607. }
  608. #endregion
  609. }
  610. }

2.UsingLock.cs

采用多线程方式,在这里,如果不是频繁的使用,其实可以不用

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Threading;
  7. namespace MySQLiteHelper
  8. {
  9. /// <summary>
  10. /// 使用using代替lock操作的对象,可指定写入和读取锁定模式
  11. /// </summary>
  12. public sealed class ClsLock
  13. {
  14. #region 内部类
  15. /// <summary>
  16. /// 利用IDisposable的using语法糖方便的释放锁定操作内部类
  17. /// </summary>
  18. private struct Lock : IDisposable
  19. {
  20. /// <summary>
  21. /// 读写锁对象
  22. /// </summary>
  23. private readonly ReaderWriterLockSlim _Lock;
  24. /// <summary>
  25. /// 是否为写入模式
  26. /// </summary>
  27. private bool _IsWrite;
  28. /// <summary>
  29. /// 利用IDisposable的using语法糖方便的释放锁定操作构造函数
  30. /// </summary>
  31. /// <param name="rwl">读写锁</param>
  32. /// <param name="isWrite">写入模式为true,读取模式为false</param>
  33. public Lock(ReaderWriterLockSlim rwl, bool isWrite)
  34. {
  35. _Lock = rwl;
  36. _IsWrite = isWrite;
  37. }
  38. /// <summary>
  39. /// 释放对象时退出指定锁定模式
  40. /// </summary>
  41. public void Dispose()
  42. {
  43. if (_IsWrite)
  44. {
  45. if (_Lock.IsWriteLockHeld)
  46. {
  47. _Lock.ExitWriteLock();
  48. }
  49. }
  50. else
  51. {
  52. if (_Lock.IsReadLockHeld)
  53. {
  54. _Lock.ExitReadLock();
  55. }
  56. }
  57. }
  58. }
  59. /// <summary>
  60. /// 空的可释放对象,免去了调用时需要判断是否为null的问题内部类
  61. /// </summary>
  62. private class Disposable : IDisposable
  63. {
  64. /// <summary>
  65. /// 空的可释放对象
  66. /// </summary>
  67. public static readonly Disposable Empty = new Disposable();
  68. /// <summary>
  69. /// 空的释放方法
  70. /// </summary>
  71. public void Dispose() { }
  72. }
  73. #endregion
  74. /// <summary>
  75. /// 读写锁
  76. /// </summary>
  77. private readonly ReaderWriterLockSlim _LockSlim = new ReaderWriterLockSlim();
  78. /// <summary>
  79. /// 使用using代替lock操作的对象,可指定写入和读取锁定模式构造函数
  80. /// </summary>
  81. public ClsLock()
  82. {
  83. Enabled = true;
  84. }
  85. /// <summary>
  86. /// 是否启用,当该值为false时,Read()和Write()方法将返回 Disposable.Empty
  87. /// </summary>
  88. public bool Enabled { get; set; }
  89. /// <summary>
  90. /// 进入读取锁定模式,该模式下允许多个读操作同时进行,
  91. /// 退出读锁请将返回对象释放,建议使用using语块,
  92. /// Enabled为false时,返回Disposable.Empty,
  93. /// 在读取或写入锁定模式下重复执行,返回Disposable.Empty;
  94. /// </summary>
  95. public IDisposable Read()
  96. {
  97. if (Enabled == false || _LockSlim.IsReadLockHeld || _LockSlim.IsWriteLockHeld)
  98. {
  99. return Disposable.Empty;
  100. }
  101. else
  102. {
  103. _LockSlim.EnterReadLock();
  104. return new Lock(_LockSlim, false);
  105. }
  106. }
  107. /// <summary>
  108. /// 进入写入锁定模式,该模式下只允许同时执行一个读操作,
  109. /// 退出读锁请将返回对象释放,建议使用using语块,
  110. /// Enabled为false时,返回Disposable.Empty,
  111. /// 在写入锁定模式下重复执行,返回Disposable.Empty
  112. /// </summary>
  113. /// <exception cref="NotImplementedException">读取模式下不能进入写入锁定状态</exception>
  114. public IDisposable Write()
  115. {
  116. if (Enabled == false || _LockSlim.IsWriteLockHeld)
  117. {
  118. return Disposable.Empty;
  119. }
  120. else if (_LockSlim.IsReadLockHeld)
  121. {
  122. throw new NotImplementedException("读取模式下不能进入写入锁定状态");
  123. }
  124. else
  125. {
  126. _LockSlim.EnterWriteLock();
  127. return new Lock(_LockSlim, true);
  128. }
  129. }
  130. }
  131. }

3.Form1.cs

窗体部分,界面如下

代码:

  1. using MySQLiteHelper;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.SQLite;
  6. using System.Windows.Forms;
  7. namespace SQLiteDemo
  8. {
  9. public partial class Form1 : Form
  10. {
  11. public Form1()
  12. {
  13. InitializeComponent();
  14. }
  15. private SQLiteHelper SQLiteHelpers = null;
  16. private const string DBAddress = "D:\\SQLiteData\\test_record.db3";
  17. private void Form1_Load(object sender, EventArgs e)
  18. {
  19. SQLiteHelpers = new SQLiteHelper(DBAddress,"123456");
  20. }
  21. /// <summary>
  22. /// 打开数据库
  23. /// </summary>
  24. /// <param name="sender"></param>
  25. /// <param name="e"></param>
  26. private void Button_OpenDB_Click(object sender, EventArgs e)
  27. {
  28. SQLiteHelpers.Open();
  29. Label_DBOpenState.Text = "打开";
  30. }
  31. /// <summary>
  32. /// 关闭数据库
  33. /// </summary>
  34. /// <param name="sender"></param>
  35. /// <param name="e"></param>
  36. private void Button_CloseDB_Click(object sender, EventArgs e)
  37. {
  38. SQLiteHelpers.Close();
  39. Label_DBOpenState.Text = "关闭";
  40. }
  41. /// <summary>
  42. /// 查询
  43. /// </summary>
  44. /// <param name="sender"></param>
  45. /// <param name="e"></param>
  46. private void Button_Query_Click(object sender, EventArgs e)
  47. {
  48. SQLiteParameter[] parameter = new SQLiteParameter[]
  49. {
  50. new SQLiteParameter("address", "济南")
  51. };
  52. string sql = "SELECT * FROM student WHERE address = @address";
  53. DataSet dataSet = SQLiteHelpers.ExecuteDataSet(sql, parameter);
  54. if (dataSet != null)
  55. {
  56. dataGridView1.DataSource = dataSet.Tables[0];
  57. }
  58. }
  59. /// <summary>
  60. /// 插入数据
  61. /// </summary>
  62. /// <param name="sender"></param>
  63. /// <param name="e"></param>
  64. private void Button_Add_Click(object sender, EventArgs e)
  65. {
  66. Dictionary<string, object> dic = new Dictionary<string, object>();
  67. dic.Add("ID", 6);
  68. dic.Add("name", "王二麻子");
  69. dic.Add("age", 44);
  70. dic.Add("address", "陕西");
  71. int result = SQLiteHelpers.InsertData("student", dic);
  72. Console.WriteLine("插入结果,受影响的行数:" + result);
  73. }
  74. /// <summary>
  75. /// 修改数据
  76. /// </summary>
  77. /// <param name="sender"></param>
  78. /// <param name="e"></param>
  79. private void Button_Modify_Click(object sender, EventArgs e)
  80. {
  81. Dictionary<string, object> dic = new Dictionary<string, object>();
  82. //将列名 name 的值改为 “猴子”
  83. dic.Add("name", "猴子");
  84. //将列名 address 的值改为 花果山
  85. dic.Add("address", "花果山");
  86. //where条件
  87. string where = "ID = @ID AND age = @Age";
  88. //where条件中对应的参数
  89. SQLiteParameter[] parameter = new SQLiteParameter[]
  90. {
  91. new SQLiteParameter("ID", 4),
  92. new SQLiteParameter("Age",23)
  93. };
  94. int result = SQLiteHelpers.Update("student", dic, where, parameter);
  95. Console.WriteLine("修改结果,受影响的行数:" + result);
  96. }
  97. /// <summary>
  98. /// 删除数据
  99. /// </summary>
  100. /// <param name="sender"></param>
  101. /// <param name="e"></param>
  102. private void Button_Delete_Click(object sender, EventArgs e)
  103. {
  104. //where条件
  105. string where = "ID = @ID";
  106. //where条件中对应的参数
  107. SQLiteParameter[] parameter = new SQLiteParameter[]
  108. {
  109. new SQLiteParameter("ID", 6),
  110. };
  111. int result = SQLiteHelpers.Delete("student", where, parameter);
  112. Console.WriteLine("删除结果,受影响的行数:" + result);
  113. }
  114. /// <summary>
  115. /// 判断表是否存在
  116. /// </summary>
  117. /// <param name="sender"></param>
  118. /// <param name="e"></param>
  119. private void Button_TableExists_Click(object sender, EventArgs e)
  120. {
  121. string title = "dddd";
  122. bool result = SQLiteHelpers.TableExists(title);
  123. Console.WriteLine(string.Format("{0} 表是否存在,结果:{1}", title, result));
  124. }
  125. //输出各表中的数据
  126. //public static void PrintValues(DataSet ds)
  127. //{
  128. // foreach (DataTable table in ds.Tables)
  129. // {
  130. // Console.WriteLine("表名称:" + table.TableName);
  131. // foreach (DataRow row in table.Rows)
  132. // {
  133. // foreach (DataColumn column in table.Columns)
  134. // {
  135. // Console.Write(row[column] + "");
  136. // }
  137. // Console.WriteLine();
  138. // }
  139. // }
  140. //}
  141. }
  142. }

上面就是所有的源码,代码比较长,你忍一下,其实也没有很复杂的部分,下面是项目的源码,有兴趣的可以支持一下我了,嘿嘿~

项目源码:点击下载

三、代码还需要改进部分

上面的代码我不觉得是完美的,由于时间关系,读者可以自己去实现这些功能:

1.去掉多线程

如果不想用多线程可以去掉UsingLock.cs ,在SQLiteHelper.cs中删除对应的引用即可。

2.封装创建数据库部分

创建数据库文件,可以从代码中分离成单独的方法。比如创建有密码的数据库文件。

创建数据库文件方式有多种,不一定要用上述代码中的写法,也可以参考下面方式:

1)编辑器,如:SQLiteStudio,Navicat 15 for SQLite 等,参考帖子:点击跳转

2)在SQLiteHelper.cs中创建数据库文件使用的是 SQLiteConnection.CreateFile(DataFile) 这句代码创建的数据库文件,其实不用这句一样可以创建数据库文件,如下:

  1. /// <summary>
  2. /// 创建数据库
  3. /// </summary>
  4. /// <param name="fileName">数据库文件路径</param>
  5. /// <param name="password">数据库密码</param>
  6. /// <returns>返回结果字符串,不为空则为错误信息</returns>
  7. public static string CreateDB(string fileName, string password)
  8. {
  9. try
  10. {
  11. string[] parmArr = new string[] { "Data Source=", fileName, ";Version=3;" };
  12. string connStr = string.Concat(parmArr);
  13. SQLiteConnection conn = new SQLiteConnection(connStr);
  14. conn.Open();
  15. // 为数据库设置密码
  16. conn.ChangePassword(password);
  17. conn.Close();
  18. return string.Empty;
  19. }
  20. catch (Exception ex)
  21. {
  22. return ex.Message;
  23. }
  24. }

运行 SQLiteConnection.open 就会创建一个空的指定名字的数据库文件。

3.影响行数为0的SQL语句

在执行SQL语句时,有些语句执行成功,也不会有影响行数。比如,创建表,删除表,此时执行SQL语句返回的影响行数就为0。执行完后,你不知道是否执行成功

4.返回值的改进

只要SQL语句不报错就是执行成功的,在方法的返回值可以改为多个,比如用 :

Tuple<bool, string, int> 第一个参数 bool 代表执行结果,第二个参数 string 代表错误信息,第三个参数 int 代表影响的行数。

Tuple<bool, string, DataSet> 第一个参数 bool 代表执行结果,第二个参数 string 代表错误信息,第三个参数 DataSet 代表返回的表单数据。

----------------------------------------

2022.06.13

由于时间问题,当时代码并没有那么完善,于是我根据上面所描述的特点进行了改进行,并增加了一些新的功能,比如创建有密码的数据库等,现在改进版本现在已经完成了,界面如下

有兴趣的大佬可以支持我一下,在此先行谢过了。

源码:点击下载

end

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/173915
推荐阅读
相关标签
  

闽ICP备14008679号