WPF桌面端开发14-Sqlite

前言

安装

NuGet中查找System.Data.SQLite进行安装

或者使用命令

1
Install-Package System.Data.SQLite -Version 1.0.113.1

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Reflection;

namespace SchoolClient.Utils
{
public class ZSqliteUtil
{
private static readonly string Dbfolder = AppDomain.CurrentDomain.BaseDirectory + "db\\";
private static readonly string Dbpath = Dbfolder + "db.sqlite";

private static SQLiteConnection _cn;

private static SQLiteConnection GetConnect()
{
if (_cn == null)
{
DirectoryInfo di = new DirectoryInfo(Dbfolder);
if (!di.Exists)
{
Directory.CreateDirectory(Dbfolder);
}
_cn = new SQLiteConnection("data source=" + Dbpath);
_cn.Open();
}
return _cn;
}

/// <summary>
/// 删除库
/// </summary>
public static void DeleteDb()
{
if (_cn != null && _cn.State == ConnectionState.Open)
{
_cn.Close();
if (File.Exists(Dbpath))
{
File.Delete(Dbpath);
}
}
}

/// <summary>
/// 创建表
/// </summary>
/// <param name="sql"></param>
public static void CreateTable(string sql)
{
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = sql };
cmd.ExecuteNonQuery();
}

/// <summary>
/// 删除表
/// </summary>
/// <param name="tablename"></param>
public static void DeleteTable(string tablename)
{
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = "DROP TABLE IF EXISTS " + tablename };
cmd.ExecuteNonQuery();
}

/// <summary>
/// 增加/删除/修改数据
/// </summary>
/// <param name="sql"></param>
/// <param name="dic"></param>
/// <returns></returns>
public static int UpdateData(string sql, Dictionary<string, object> dic)
{
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = sql };
foreach (KeyValuePair<string, object> kvp in dic)
{
if (kvp.Value is int)
{
cmd.Parameters.Add(kvp.Key, DbType.Int32).Value = kvp.Value;
}
else if (kvp.Value is long)
{
cmd.Parameters.Add(kvp.Key, DbType.Int64).Value = kvp.Value;
}
else if (kvp.Value is string)
{
cmd.Parameters.Add(kvp.Key, DbType.String).Value = kvp.Value;
}
}
return cmd.ExecuteNonQuery();
}

/// <summary>
/// 批量增加/删除/修改数据
/// </summary>
/// <param name="sql"></param>
/// <param name="dicList"></param>
public static void UpdateDataBatch(string sql, List<Dictionary<string, object>> dicList)
{
SQLiteConnection conn = GetConnect();
SQLiteCommand cmd = new SQLiteCommand { Connection = conn };
SQLiteTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
foreach (Dictionary<string, object> dic in dicList)
{
cmd.CommandText = sql;
foreach (KeyValuePair<string, object> kvp in dic)
{
if (kvp.Value is int)
{
cmd.Parameters.Add(kvp.Key, DbType.Int32).Value = kvp.Value;
}
else if (kvp.Value is long)
{
cmd.Parameters.Add(kvp.Key, DbType.Int64).Value = kvp.Value;
}
else if (kvp.Value is string)
{
cmd.Parameters.Add(kvp.Key, DbType.String).Value = kvp.Value;
}
}
cmd.ExecuteNonQuery();
}
tx.Commit();
}
catch (SQLiteException e)
{
tx.Rollback();
throw new Exception(e.Message);
}
}

public static int UpdateData(string sql)
{
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = sql };
return cmd.ExecuteNonQuery();
}

/// <summary>
/// 清空表数据
/// </summary>
/// <param name="tablename"></param>
/// <returns></returns>
public static int DeleteAllData(string tablename)
{
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = "delete from " + tablename };
return cmd.ExecuteNonQuery();
}

/// <summary>
/// 查询数据
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static List<T> QueryData<T>(string sql) where T : class, new()
{
//Console.WriteLine("sql:"+ sql);
List<T> list = new List<T>();
PropertyInfo[] propArr = new T().GetType().GetProperties();
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = sql };
SQLiteDataReader sr = cmd.ExecuteReader();
while (sr.Read())
{
T itemModel = new T();
foreach (PropertyInfo property in propArr)
{
try
{
object value = sr[property.Name];
if (property.PropertyType == typeof(int))
{
value = int.Parse(value.ToString());
}
if (property.PropertyType == typeof(float))
{
value = float.Parse(value.ToString());
}
property.SetValue(
itemModel,
value,
null
);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine($@"数据库中不包含:{property.Name}");
}
catch (Exception ex)
{
Console.WriteLine($@"Exception:{property.Name} {ex.Message}");
}
}
list.Add(itemModel);
}
sr.Close();
return list;
}

/// <summary>
/// 查询数据条数
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static int QueryCount(string sql)
{
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = sql };
SQLiteDataReader sr = cmd.ExecuteReader();
sr.Read();
int count = sr.GetInt32(0);
sr.Close();
return count;
}

/// <summary>
/// 遍历查询表结构
/// </summary>
public static void QueryAllTableInfo()
{
SQLiteCommand cmd = new SQLiteCommand { Connection = GetConnect(), CommandText = "SELECT name FROM sqlite_master WHERE TYPE='table' " };
SQLiteDataReader sr = cmd.ExecuteReader();
List<string> tables = new List<string>();
while (sr.Read())
{
tables.Add(sr.GetString(0));
}
//datareader 必须要先关闭,否则 commandText 不能赋值
sr.Close();
foreach (string a in tables)
{
cmd.CommandText = $"PRAGMA TABLE_INFO({a})";
Console.WriteLine($@"-------- 表名:{a} --------");
sr = cmd.ExecuteReader();
while (sr.Read())
{
Console.WriteLine($@"{sr[0]} {sr[1]} {sr[2]} {sr[3]}");
}
sr.Close();
Console.WriteLine(@"");
}
}
}
}

注意

不要每次操作都打开关闭数据库连接,容易数据库锁死。

使用

相关实体类

1
2
3
4
5
6
7
8
9
10
public class ClassData
{
public long unix { get; set; }

public string api { get; set; }

public string json { get; set; }

public long askid { get; set; }
}

创建库

1
ZSqliteUtil.DeleteTable("TClassData");

创建表

1
ZSqliteUtil.CreateTable("CREATE TABLE IF NOT EXISTS TClassData(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,unix INTERGER,api TEXT,json TEXT,askid INTERGER)");

插入数据

1
2
3
4
5
6
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("unix", data.unix);
dic.Add("api", data.api);
dic.Add("json", data.json);
dic.Add("askid", data.askid);
ZSqliteUtil.UpdateData("INSERT INTO TClassData(unix,api,json,askid) VALUES(@unix,@api,@json,@askid)", dic);

查询数据

1
ZSqliteUtil.QueryData<ClassData>("select * from TClassData");

注意

Sqlite中的integer类型获取的时候都是long类型,如果对象的属性类型是int,会注入失败,要进行判断转换。