当前位置:   article > 正文

.Net SQLite 简单使用

.net sqlite

安装Nuget

  1. /// <summary>
  2. /// 创建数据表字段类型
  3. /// </summary>
  4. public enum AttrsType
  5. {
  6. Self = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
  7. Default
  8. }
  1. using ChromeDefaultUI.Enums;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Data.SQLite;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace ChromeDefaultUI.sqlite
  11. {
  12. public class SQLHelper
  13. {
  14. private static SQLHelper helper = new SQLHelper();
  15. public static SQLHelper Instance
  16. {
  17. get
  18. {
  19. return helper;
  20. }
  21. }
  22. private SQLHelper()
  23. {
  24. }
  25. /// <summary>
  26. /// 根据属性创建字典
  27. /// </summary>
  28. /// <param name="obj"></param>
  29. /// <returns></returns>
  30. public static Dictionary<string, string> CreateObjectData(object obj, AttrsType attrsType)
  31. {
  32. System.Reflection.PropertyInfo[] propertyInfos = obj.GetType().GetProperties((BindingFlags)attrsType);
  33. Dictionary<string, string> data = new Dictionary<string, string>();
  34. foreach (var item in propertyInfos)
  35. {
  36. string name = item.Name;
  37. string val = "";
  38. if (item.GetValue(obj) != null)
  39. {
  40. val = item.GetValue(obj).ToString();
  41. }
  42. data.Add(name, val);
  43. }
  44. return data;
  45. }
  46. /// <summary>
  47. /// 增加数据,如果没有表,则自动创建表
  48. /// </summary>
  49. /// <param name="dic">数据</param>
  50. /// <param name="tableName"></param>
  51. public int Insert(Dictionary<string, string> dic, Tables tableName)
  52. {
  53. int ins = 0;
  54. string connStr = @"URI=file:data.db";
  55. using (SQLiteConnection conn = new SQLiteConnection(connStr))
  56. {
  57. conn.Open();
  58. CreateTable(dic, conn, tableName.ToString());
  59. string key = "";
  60. string val = "";
  61. foreach (var item in dic.Keys)
  62. {
  63. key += (item + ",");
  64. val += ("'" + dic[item] + "',");
  65. }
  66. key = key.Substring(0, key.Length - 1);
  67. val = val.Substring(0, val.Length - 1);
  68. string sql = "insert into " + tableName + " (" + key + ") values (" + val + ")";
  69. using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
  70. {
  71. ins = cmd.ExecuteNonQuery();
  72. }
  73. conn.Close();
  74. }
  75. return ins;
  76. }
  77. /// <summary>
  78. /// 根据条件删除数据
  79. /// </summary>
  80. /// <param name="par">查找条件 null 或 size=0 则删除所有数据</param>
  81. /// <param name="tableName"></param>
  82. public int Delete(Dictionary<string, string> par, Tables tableName)
  83. {
  84. int del = 0;
  85. string connStr = @"URI=file:data.db";
  86. using (SQLiteConnection conn = new SQLiteConnection(connStr))
  87. {
  88. conn.Open();
  89. string sqlPar = "";
  90. if (par != null && par.Count > 0)
  91. {
  92. foreach (string item in par.Keys)
  93. {
  94. sqlPar += item + " = '" + par[item] + "' AND ";
  95. }
  96. sqlPar = sqlPar.Substring(0, sqlPar.Length - (" AND ".Length));
  97. }
  98. string sql = "Delete from " + tableName + (sqlPar.Length > 0 ? (" where " + sqlPar) : "");
  99. using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
  100. {
  101. del = cmd.ExecuteNonQuery();//exq !=0 则删除成功,exq==0则删除失败或没有此数据
  102. }
  103. conn.Close();
  104. }
  105. return del;
  106. }
  107. /// <summary>
  108. /// 通过事务删除多条
  109. /// </summary>
  110. /// <param name="par"></param>
  111. /// <param name="tableName"></param>
  112. /// <returns></returns>
  113. public int DeleteTransaction(List<Dictionary<string, string>> parList, Tables tableName)
  114. {
  115. int del = 0;
  116. string connStr = @"URI=file:data.db";
  117. using (SQLiteConnection conn = new SQLiteConnection(connStr))
  118. {
  119. conn.Open();
  120. SQLiteTransaction tr = conn.BeginTransaction();//事务开始
  121. using (SQLiteCommand cmd = new SQLiteCommand())
  122. {
  123. cmd.Connection = conn;
  124. for (int i = 0; i < parList.Count; i++)
  125. {
  126. Dictionary<string, string> par = parList[i];
  127. string sqlPar = "";
  128. if (par != null && par.Count > 0)
  129. {
  130. foreach (string item in par.Keys)
  131. {
  132. sqlPar += item + " = '" + par[item] + "' AND ";
  133. }
  134. sqlPar = sqlPar.Substring(0, sqlPar.Length - " AND ".Length);
  135. }
  136. string sql = "Delete from " + tableName + (sqlPar.Length > 0 ? (" where " + sqlPar) : "");
  137. cmd.CommandText = sql;
  138. int d = cmd.ExecuteNonQuery();//exq !=0 则删除成功,exq==0则删除失败或没有此数据
  139. if (d > 0)
  140. {
  141. del++;
  142. }
  143. }
  144. tr.Commit();
  145. }
  146. conn.Close();
  147. }
  148. return del;
  149. }
  150. /// <summary>
  151. /// 根据条件查询数据
  152. /// </summary>
  153. /// <param name="par">查找条件,null 则查询所有</param>
  154. /// <param name="tableName"></param>
  155. public int FindRows(Dictionary<string, string> par, Tables tableName)
  156. {
  157. int row = 0;
  158. string connStr = @"URI=file:data.db";
  159. using (SQLiteConnection conn = new SQLiteConnection(connStr))
  160. {
  161. conn.Open();
  162. string finTab = "select * from sqlite_master where type = 'table' and name ='" + tableName + "'";
  163. int tabCount = 0;
  164. using (SQLiteCommand cmd = new SQLiteCommand(finTab, conn))
  165. {
  166. using (SQLiteDataReader reader = cmd.ExecuteReader())
  167. {
  168. if (reader.HasRows)
  169. {
  170. while (reader.Read())
  171. {
  172. tabCount++;
  173. }
  174. }
  175. }
  176. }
  177. if (tabCount > 0)
  178. {
  179. string sqlPar = "";
  180. if (par != null && par.Count > 0)
  181. {
  182. foreach (string item in par.Keys)
  183. {
  184. sqlPar += item + " = '" + par[item] + "' AND ";
  185. }
  186. sqlPar = sqlPar.Substring(0, sqlPar.Length - (" AND ".Length));
  187. }
  188. string sql = "SELECT * FROM " + tableName + (sqlPar.Length > 0 ? (" WHERE " + sqlPar) : "");
  189. using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
  190. {
  191. using (SQLiteDataReader reader = cmd.ExecuteReader())
  192. {
  193. if (reader.HasRows)
  194. {
  195. while (reader.Read())
  196. {
  197. row++;
  198. }
  199. }
  200. }
  201. }
  202. }
  203. conn.Close();
  204. }
  205. return row;
  206. }
  207. /// <summary>
  208. /// 根据条件更新数据
  209. /// </summary>
  210. /// <param name="update">更新值</param>
  211. /// <param name="condition">条件</param>
  212. /// <param name="tableName">表名</param>
  213. /// <returns></returns>
  214. public int Update(Dictionary<string, string> update, Dictionary<string, string> condition, Tables tableName)
  215. {
  216. if (update == null || update.Count == 0 || condition == null || condition.Count == 0)
  217. {
  218. throw new Exception("条件不足");
  219. }
  220. int rowCount = 0;
  221. string connStr = @"URI=file:data.db";
  222. using (SQLiteConnection conn = new SQLiteConnection(connStr))
  223. {
  224. conn.Open();
  225. string finTab = "select * from sqlite_master where type = 'table' and name ='" + tableName + "'";
  226. int tabCount = 0;
  227. using (SQLiteCommand cmd = new SQLiteCommand(finTab, conn))
  228. {
  229. using (SQLiteDataReader reader = cmd.ExecuteReader())
  230. {
  231. if (reader.HasRows)
  232. {
  233. while (reader.Read())
  234. {
  235. tabCount++;
  236. }
  237. }
  238. }
  239. }
  240. if (tabCount > 0)
  241. {
  242. string value = UpdateValue(update);
  243. string cond = Condition(condition);
  244. string sql = "Update " + tableName + " Set " + value + " Where " + cond;
  245. using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
  246. {
  247. rowCount = cmd.ExecuteNonQuery();
  248. }
  249. }
  250. conn.Close();
  251. }
  252. return rowCount;
  253. }
  254. /// <summary>
  255. /// 根据条件反射返回obj,条件为null时,查询所有
  256. /// </summary>
  257. /// <param name="par">查找条件</param>
  258. /// <param name="tableName"></param>
  259. /// <param name="type"></param>
  260. /// <returns></returns>
  261. public ObservableCollection<Dictionary<string, object>> FindToObj(Dictionary<string, string> par, Tables tableName)
  262. {
  263. ObservableCollection<Dictionary<string, object>> o = new ObservableCollection<Dictionary<string, object>>();
  264. string connStr = @"URI=file:data.db";
  265. using (SQLiteConnection conn = new SQLiteConnection(connStr))
  266. {
  267. conn.Open();
  268. string sqlPar = "";
  269. if (par != null && par.Count > 0)
  270. {
  271. foreach (string item in par.Keys)
  272. {
  273. sqlPar += item + " = '" + par[item] + "' AND ";
  274. }
  275. sqlPar = sqlPar.Substring(0, sqlPar.Length - (" AND ".Length));
  276. }
  277. string sql = "SELECT * FROM " + tableName + (sqlPar.Length > 0 ? (" WHERE " + sqlPar) : "");
  278. using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
  279. {
  280. using (SQLiteDataReader reader = cmd.ExecuteReader())
  281. {
  282. while (reader.Read())
  283. {
  284. var vals = reader.GetValues();
  285. Dictionary<string, object> dic = new Dictionary<string, object>();
  286. foreach (var item in vals.AllKeys)
  287. {
  288. dic.Add(item, vals[item]);
  289. }
  290. o.Add(dic);
  291. }
  292. }
  293. }
  294. conn.Close();
  295. }
  296. return o;
  297. }
  298. /// <summary>
  299. /// 创建表
  300. /// </summary>
  301. /// <param name="data"></param>
  302. /// <param name="cnn"></param>
  303. /// <param name="tableName"></param>
  304. private void CreateTable(Dictionary<string, string> data, SQLiteConnection cnn, string tableName)
  305. {
  306. string v = "";
  307. foreach (var item in data.Keys)
  308. {
  309. v += item;
  310. v += " text,";
  311. }
  312. v = v.Substring(0, v.Length - 1);
  313. string sql = "Create table IF NOT EXISTS " + tableName + " (Id integer primary key, " + v + ");";
  314. SQLiteCommand cmd = new SQLiteCommand(sql, cnn);
  315. cmd.ExecuteNonQuery();
  316. }
  317. /// <summary>
  318. /// 返回条件语句
  319. /// </summary>
  320. /// <param name="condition"></param>
  321. /// <returns></returns>
  322. private static string Condition(Dictionary<string, string> condition)
  323. {
  324. string sqlPar = "";
  325. if (condition != null && condition.Count > 0)
  326. {
  327. foreach (string item in condition.Keys)
  328. {
  329. sqlPar += item + " = '" + condition[item] + "' AND ";
  330. }
  331. sqlPar = sqlPar.Substring(0, sqlPar.Length - (" AND ".Length));
  332. }
  333. return sqlPar;
  334. }
  335. /// <summary>
  336. /// 返回更新值语句
  337. /// </summary>
  338. /// <param name="condition"></param>
  339. /// <returns></returns>
  340. private static string UpdateValue(Dictionary<string, string> condition)
  341. {
  342. string sqlPar = "";
  343. if (condition != null && condition.Count > 0)
  344. {
  345. foreach (string item in condition.Keys)
  346. {
  347. sqlPar += item + " = '" + condition[item] + "' , ";
  348. }
  349. sqlPar = sqlPar.Substring(0, sqlPar.Length - (" , ".Length));
  350. }
  351. return sqlPar;
  352. }
  353. }
  354. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号