• c#Sqlite类库


    字符串转Datetime 采坑

    1.注意保存到数据库的日期格式DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

    格式不统一日期查询的时候会出现搜索不准确问题.

    2.表设计推荐使用 sqlitestudio 工具

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. namespace System.Data.SQLite
    5. {
    6. public class SQLiteColumn
    7. {
    8. public string ColumnName = "";
    9. public bool PrimaryKey = false;
    10. public ColType ColDataType = ColType.Text;
    11. public bool AutoIncrement = false;
    12. public bool NotNull = false;
    13. public string DefaultValue = "";
    14. public SQLiteColumn()
    15. { }
    16. public SQLiteColumn(string colName)
    17. {
    18. ColumnName = colName;
    19. PrimaryKey = false;
    20. ColDataType = ColType.Text;
    21. AutoIncrement = false;
    22. }
    23. public SQLiteColumn(string colName, ColType colDataType)
    24. {
    25. ColumnName = colName;
    26. PrimaryKey = false;
    27. ColDataType = colDataType;
    28. AutoIncrement = false;
    29. }
    30. public SQLiteColumn(string colName, bool autoIncrement)
    31. {
    32. ColumnName = colName;
    33. if (autoIncrement)
    34. {
    35. PrimaryKey = true;
    36. ColDataType = ColType.Integer;
    37. AutoIncrement = true;
    38. }
    39. else
    40. {
    41. PrimaryKey = false;
    42. ColDataType = ColType.Text;
    43. AutoIncrement = false;
    44. }
    45. }
    46. public SQLiteColumn(string colName, ColType colDataType, bool primaryKey, bool autoIncrement, bool notNull, string defaultValue)
    47. {
    48. ColumnName = colName;
    49. if (autoIncrement)
    50. {
    51. PrimaryKey = true;
    52. ColDataType = ColType.Integer;
    53. AutoIncrement = true;
    54. }
    55. else
    56. {
    57. PrimaryKey = primaryKey;
    58. ColDataType = colDataType;
    59. AutoIncrement = false;
    60. NotNull = notNull;
    61. DefaultValue = defaultValue;
    62. }
    63. }
    64. }
    65. }
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. namespace System.Data.SQLite
    5. {
    6. public class SQLiteColumnList : IList<SQLiteColumn>
    7. {
    8. List<SQLiteColumn> _lst = new List<SQLiteColumn>();
    9. private void CheckColumnName(string colName)
    10. {
    11. for (int i = 0; i < _lst.Count; i++)
    12. {
    13. if (_lst[i].ColumnName == colName)
    14. throw new Exception("Column name of \"" + colName + "\" is already existed.");
    15. }
    16. }
    17. public int IndexOf(SQLiteColumn item)
    18. {
    19. return _lst.IndexOf(item);
    20. }
    21. public void Insert(int index, SQLiteColumn item)
    22. {
    23. CheckColumnName(item.ColumnName);
    24. _lst.Insert(index, item);
    25. }
    26. public void RemoveAt(int index)
    27. {
    28. _lst.RemoveAt(index);
    29. }
    30. public SQLiteColumn this[int index]
    31. {
    32. get
    33. {
    34. return _lst[index];
    35. }
    36. set
    37. {
    38. if (_lst[index].ColumnName != value.ColumnName)
    39. {
    40. CheckColumnName(value.ColumnName);
    41. }
    42. _lst[index] = value;
    43. }
    44. }
    45. public void Add(SQLiteColumn item)
    46. {
    47. CheckColumnName(item.ColumnName);
    48. _lst.Add(item);
    49. }
    50. public void Clear()
    51. {
    52. _lst.Clear();
    53. }
    54. public bool Contains(SQLiteColumn item)
    55. {
    56. return _lst.Contains(item);
    57. }
    58. public void CopyTo(SQLiteColumn[] array, int arrayIndex)
    59. {
    60. _lst.CopyTo(array, arrayIndex);
    61. }
    62. public int Count
    63. {
    64. get { return _lst.Count; }
    65. }
    66. public bool IsReadOnly
    67. {
    68. get { return false; }
    69. }
    70. public bool Remove(SQLiteColumn item)
    71. {
    72. return _lst.Remove(item);
    73. }
    74. public IEnumerator<SQLiteColumn> GetEnumerator()
    75. {
    76. return _lst.GetEnumerator();
    77. }
    78. Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
    79. {
    80. return _lst.GetEnumerator();
    81. }
    82. }
    83. }
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. namespace System.Data.SQLite
    5. {
    6. public class SQLiteTable
    7. {
    8. public string TableName = "";
    9. public SQLiteColumnList Columns = new SQLiteColumnList();
    10. public SQLiteTable()
    11. { }
    12. public SQLiteTable(string name)
    13. {
    14. TableName = name;
    15. }
    16. }
    17. }

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using System.Data;
    5. using System.Globalization;
    6. using System.IO;
    7. namespace System.Data.SQLite
    8. {
    9. public enum ColType
    10. {
    11. Text,
    12. DateTime,
    13. Integer,
    14. Decimal,
    15. BLOB
    16. }
    17. public class SQLiteHelper
    18. {
    19. public static string ConnectionString = "路径";
    20. public string Error = "";
    21. /// <summary>
    22. /// 创建数据库
    23. /// </summary>
    24. public bool CreateDataBase()
    25. {
    26. string path = Path.GetDirectoryName(ConnectionString.Replace("data source=", ""));
    27. if ((!string.IsNullOrWhiteSpace(path)) && (!Directory.Exists(path)))
    28. {
    29. Directory.CreateDirectory(path);
    30. }
    31. if (!File.Exists(ConnectionString))
    32. {
    33. SQLiteConnection.CreateFile(ConnectionString);
    34. }
    35. return true;
    36. }
    37. //创建表代码:
    38. //SQLiteTable tb = new SQLiteTable("person");
    39. //tb.Columns.Add(new SQLiteColumn("id", true));
    40. //tb.Columns.Add(new SQLiteColumn("name"));
    41. //tb.Columns.Add(new SQLiteColumn("membershipid", ColType.Integer));
    42. //tb.Columns.Add(new SQLiteColumn("level", ColType.Decimal, false, false, "5.5"));
    43. //sh.CreateTable(tb);
    44. /// <summary>
    45. /// 创建表
    46. /// </summary>
    47. /// <param name="table"></param>
    48. /// <returns></returns>
    49. public bool CreateTable(SQLiteTable table)
    50. {
    51. StringBuilder sb = new Text.StringBuilder();
    52. sb.Append("create table if not exists `");
    53. sb.Append(table.TableName);
    54. sb.AppendLine("`(");
    55. bool firstRecord = true;
    56. foreach (SQLiteColumn col in table.Columns)
    57. {
    58. if (col.ColumnName.Trim().Length == 0)
    59. {
    60. throw new Exception("Column name cannot be blank.");
    61. }
    62. if (firstRecord)
    63. firstRecord = false;
    64. else
    65. sb.AppendLine(",");
    66. sb.Append(col.ColumnName);
    67. sb.Append(" ");
    68. if (col.AutoIncrement)
    69. {
    70. sb.Append("integer primary key autoincrement");
    71. continue;
    72. }
    73. switch (col.ColDataType)
    74. {
    75. case ColType.Text:
    76. sb.Append("text"); break;
    77. case ColType.Integer:
    78. sb.Append("integer"); break;
    79. case ColType.Decimal:
    80. sb.Append("decimal"); break;
    81. case ColType.DateTime:
    82. sb.Append("datetime"); break;
    83. case ColType.BLOB:
    84. sb.Append("blob"); break;
    85. }
    86. if (col.PrimaryKey)
    87. sb.Append(" primary key");
    88. else if (col.NotNull)
    89. sb.Append(" not null");
    90. else if (col.DefaultValue.Length > 0)
    91. {
    92. sb.Append(" default ");
    93. if (col.DefaultValue.Contains(" ") || col.ColDataType == ColType.Text || col.ColDataType == ColType.DateTime)
    94. {
    95. sb.Append("'");
    96. sb.Append(col.DefaultValue);
    97. sb.Append("'");
    98. }
    99. else
    100. {
    101. sb.Append(col.DefaultValue);
    102. }
    103. }
    104. }
    105. sb.AppendLine(");");
    106. try
    107. {
    108. using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
    109. {
    110. conn.Open();
    111. SQLiteCommand comm = new SQLiteCommand();
    112. comm.Connection = conn;
    113. comm.CommandText = sb.ToString();
    114. comm.CommandType = CommandType.Text;
    115. comm.CommandTimeout = conn.ConnectionTimeout;
    116. comm.ExecuteNonQuery();
    117. conn.Close();
    118. }
    119. return true;
    120. }
    121. catch (Exception ex)
    122. {
    123. Error = "系统故障:GetDataSetBySQLString," + ex.ToString();
    124. return false;
    125. }
    126. }
    127. /// <summary>
    128. /// 查询数据
    129. /// </summary>
    130. public DataTable GetDataTableBySql(string sql)
    131. {
    132. return GetDataSetBySQLString(sql).Tables[0];
    133. }
    134. public DataSet GetDataSetBySQLString(string SQLString)
    135. {
    136. try
    137. {
    138. using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
    139. {
    140. conn.Open();
    141. SQLiteCommand comm = new SQLiteCommand();
    142. comm.Connection = conn;
    143. comm.CommandText = SQLString;
    144. comm.CommandType = CommandType.Text;
    145. comm.CommandTimeout = conn.ConnectionTimeout;
    146. DataSet ds = new DataSet("SQLDataSet");
    147. SQLiteDataAdapter adapter = new SQLiteDataAdapter();
    148. adapter.SelectCommand = comm;
    149. adapter.Fill(ds, "SQLDataSet");
    150. conn.Close();
    151. return ds;
    152. }
    153. }
    154. catch (Exception ex)
    155. {
    156. Error = "系统故障:GetDataSetBySQLString," + ex.ToString();
    157. return null;
    158. }
    159. }
    160. /// <summary>
    161. /// 添加或更新数据
    162. /// </summary>
    163. public int UpdateBySQL(string sql)
    164. {
    165. using (SQLiteConnection con = new SQLiteConnection(ConnectionString))
    166. {
    167. con.Open();
    168. SQLiteCommand cmd = null;
    169. try
    170. {
    171. cmd = new SQLiteCommand(sql, con);
    172. object objResult = cmd.ExecuteScalar();
    173. con.Close();
    174. if (objResult == null)
    175. {
    176. return 0;
    177. }
    178. else
    179. {
    180. return 1;
    181. }
    182. }
    183. catch (Exception ex)
    184. {
    185. Error = ex.ToString();
    186. con.Close();
    187. Error = "系统故障:UpdateBySQL," + ex.ToString();
    188. return -1;
    189. }
    190. }
    191. }
    192. /// <summary>
    193. /// 删除数据库数据
    194. /// </summary>
    195. public int DeltetBySQL(string sql)
    196. {
    197. using (SQLiteConnection con = new SQLiteConnection(ConnectionString))
    198. {
    199. con.Open();
    200. SQLiteCommand cmd = null;
    201. try
    202. {
    203. cmd = new SQLiteCommand(sql, con);
    204. int objResult = cmd.ExecuteNonQuery();
    205. con.Close();
    206. return 0;
    207. }
    208. catch (Exception ex)
    209. {
    210. Error = ex.ToString();
    211. con.Close();
    212. Error = "系统故障:DeltetBySQL," + ex.ToString();
    213. return -1;
    214. }
    215. }
    216. }
    217. }
    218. }

    调用方法

    SQLiteHelper.ConnectionString ="data source=F:\db\Db_Phone";

    //创建数据库

    SQLiteHelper sh = new SQLiteHelper();

    //创建表
    SQLiteTable tb = new SQLiteTable("person");
    tb.Columns.Add(new SQLiteColumn("id", true));
    tb.Columns.Add(new SQLiteColumn("name"));
    tb.Columns.Add(new SQLiteColumn("membershipid", ColType.Integer));
    tb.Columns.Add(new SQLiteColumn("level", ColType.Decimal, false, false, "5.5"));
    sh.CreateTable(tb);

    //调用语句

    string sql = string.Format("INSERT INTO PicFiles (SN,Path,Createdate) VALUES ('{0}','{1}','{2}')", "fan", "wen", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                int rel = sh.UpdateBySQL(sql);

  • 相关阅读:
    【20220903-美团笔试】
    二分查找总结
    单线程、多线程Reactor模型
    第七章 排序
    内核IPv4路由选择子系统(简述)
    选择工业交换机时,需要关注哪些方面的性能?
    java实现国密算法SM3摘要加密
    云原生之nacos架构一览解读
    MindSpore:CUDA编程(一)在WSL ubuntu 20.04上安装CUDA环境
    Linux软件包管理— rpm软件包查询
  • 原文地址:https://blog.csdn.net/fanwenhu/article/details/125480785