0
点赞
收藏
分享

微信扫一扫

C#操作SQLite数据库

我们在开发应用是经常会需要用到一些数据的存储,存储的方式有多种,使用数据库是一种比较受大家欢迎的方式。但是对于一些小型的应用,如一些移动APP,通常的数据库过于庞大,而轻便的SQLite则能解决这一问题。不但操作方便,而且只需要要一个文件即可,在这里我们来说一说使用C#语言操作SQLite数据库。

1SQLite简介

SQLite,是一款轻型的数据库,是遵守​​ACID​​​的关系型​​数据库管理系统​​​,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是​​嵌入式​​​的,而且目前已经在很多​​嵌入式产品​​​中使用了它,它占用资源非常的低,在​​嵌入式设备​​​中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的​​操作系统​​​,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起MySQL、PostgreSQL这两款开源的世界著名​​数据库管理系统​​来讲,它的处理速度比他们都快。

如果想了解更多关于SQLite的问题,可以访问它的官方网站:http://www.sqlite.org/

2、开始前的准备

在开始之前我们需要准备必要的开发环境,这次咱们使用的是Visual Studio 2015开发环境,但是我们开发基于SQLite的应用光有VS2015还不够。我需要到SQLite的官方网站下载并安装SQLite。

在SQLite官网找到下载,有应用于各种环境的SQLite组件及源码,我们选择Precompiled Binaries for .NET,这是应用于.NET开发环境的,点击进入会看到应用于.NET2.0直至4.6以及32位和64位平台的各个版本。我们选择Setups for 32-bit Windows (.NET Framework 4.6)下载安装即可。

3C#操作SQLite的封装

在完成开发环境的准备之后,我们接下来实现对SQLite操作的必要封装,以进一步降低在具体应用中的使用难度。在这里我们只是封装一些常用而且必要的功能。

1     public class SQLiteHelper
2 {
3 //创建数据库文件
4 public static void CreateDBFile(string fileName)
5 {
6 string path = System.Environment.CurrentDirectory + @"/Data/";
7 if (!Directory.Exists(path))
8 {
9 Directory.CreateDirectory(path);
10 }
11 string databaseFileName = path + fileName;
12 if (!File.Exists(databaseFileName))
13 {
14 SQLiteConnection.CreateFile(databaseFileName);
15 }
16 }
17
18 //生成连接字符串
19 private static string CreateConnectionString()
20 {
21 SQLiteConnectionStringBuilder connectionString = new SQLiteConnectionStringBuilder();
22 connectionString.DataSource = @"data/ScriptHelper.db";
23
24 string conStr = connectionString.ToString();
25 return conStr;
26 }
27
28 /// <summary>
29 /// 对插入到数据库中的空值进行处理
30 /// </summary>
31 /// <param name="value"></param>
32 /// <returns></returns>
33 public static object ToDbValue(object value)
34 {
35 if (value == null)
36 {
37 return DBNull.Value;
38 }
39 else
40 {
41 return value;
42 }
43 }
44
45 /// <summary>
46 /// 对从数据库中读取的空值进行处理
47 /// </summary>
48 /// <param name="value"></param>
49 /// <returns></returns>
50 public static object FromDbValue(object value)
51 {
52 if (value == DBNull.Value)
53 {
54 return null;
55 }
56 else
57 {
58 return value;
59 }
60 }
61
62 /// <summary>
63 /// 执行非查询的数据库操作
64 /// </summary>
65 /// <param name="sqlString">要执行的sql语句</param>
66 /// <param name="parameters">参数列表</param>
67 /// <returns>返回受影响的条数</returns>
68 public static int ExecuteNonQuery(string sqlString, params SQLiteParameter[] parameters)
69 {
70 string connectionString=CreateConnectionString();
71 using (SQLiteConnection conn = new SQLiteConnection(connectionString))
72 {
73 conn.Open();
74 using (SQLiteCommand cmd = conn.CreateCommand())
75 {
76 cmd.CommandText = sqlString;
77 foreach (SQLiteParameter parameter in parameters)
78 {
79 cmd.Parameters.Add(parameter);
80 }
81 return cmd.ExecuteNonQuery();
82 }
83 }
84 }
85
86 /// <summary>
87 /// 执行查询并返回查询结果第一行第一列
88 /// </summary>
89 /// <param name="sqlString">SQL语句</param>
90 /// <param name="sqlparams">参数列表</param>
91 /// <returns></returns>
92 public static object ExecuteScalar(string sqlString, params SQLiteParameter[] parameters)
93 {
94 string connectionString = CreateConnectionString();
95 using (SQLiteConnection conn = new SQLiteConnection(connectionString))
96 {
97 conn.Open();
98 using (SQLiteCommand cmd = conn.CreateCommand())
99 {
100 cmd.CommandText = sqlString;
101 foreach (SQLiteParameter parameter in parameters)
102 {
103 cmd.Parameters.Add(parameter);
104 }
105 return cmd.ExecuteScalar();
106 }
107 }
108 }
109
110 /// <summary>
111 /// 查询多条数据
112 /// </summary>
113 /// <param name="sqlString">SQL语句</param>
114 /// <param name="parameters">参数列表</param>
115 /// <returns>返回查询的数据表</returns>
116 public static DataTable GetDataTable(string sqlString,params SQLiteParameter[] parameters)
117 {
118 string connectionString = CreateConnectionString();
119 using (SQLiteConnection conn = new SQLiteConnection(connectionString))
120 {
121 conn.Open();
122 using (SQLiteCommand cmd = conn.CreateCommand())
123 {
124 cmd.CommandText = sqlString;
125 foreach (SQLiteParameter parameter in parameters)
126 {
127 cmd.Parameters.Add(parameter);
128 }
129 DataSet ds = new DataSet();
130 SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
131 adapter.Fill(ds);
132 return ds.Tables[0];
133 }
134 }
135 }
136 }

4、应用实例

上面封装完了之后,我们就是使用上面封装的函数来实际操作SQLite数据库。对数据库的应用实例无非就是对各种对象的增、删、改、查。我没列举一个对源码类型对象的各种操作实例如下:

1     public class ScriptTypeDAL
2 {
3 public ScriptTypeM ToScriptType(DataRow row)
4 {
5 ScriptTypeM type = new ScriptTypeM();
6 type.ScriptTypeId = (Guid)row["ScriptTypeId"];
7 type.ScriptType = (string)row["ScriptType"];
8 type.IsUsing = (bool)row["IsUsing"];
9 return type;
10 }
11
12 public void Insert(ScriptTypeM Type)
13 {
14 SQLiteHelper.ExecuteNonQuery(@"insert into TB_ScriptType(ScriptTypeId,ScriptType,IsUsing)
15 Values(@ScriptTypeId,@ScriptType,1)",
16 new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId),
17 new SQLiteParameter("ScriptType", Type.ScriptType));
18
19 }
20
21 public void Update(ScriptTypeM Type)
22 {
23 SQLiteHelper.ExecuteNonQuery(@"update TB_ScriptType set ScriptType=@ScriptType,
24 IsUsing=@IsUsing where ScriptTypeId=@ScriptTypeId",
25 new SQLiteParameter("ScriptType", Type.ScriptType),
26 new SQLiteParameter("IsUsing", Type.IsUsing),
27 new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId));
28 }
29
30 public ScriptTypeM GetbyId(Guid id)
31 {
32 DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where ScriptTypeId=@id",
33 new SQLiteParameter("id", id));
34 if (table.Rows.Count <= 0)
35 {
36 return null;
37 }
38 else if (table.Rows.Count > 1)
39 {
40 throw new Exception("Id重复!");
41 }
42 else
43 {
44 return ToScriptType(table.Rows[0]);
45 }
46 }
47
48 public ScriptTypeM GetbyName(string name)
49 {
50 DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where ScriptType=@name",
51 new SQLiteParameter("name", name));
52 if (table.Rows.Count <= 0)
53 {
54 return null;
55 }
56 else if (table.Rows.Count > 1)
57 {
58 throw new Exception("类型名称重复!");
59 }
60 else
61 {
62 return ToScriptType(table.Rows[0]);
63 }
64 }
65
66 public ScriptTypeM[] ListAll()
67 {
68 DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where IsUsing=1");
69 ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];
70 for (int i = 0; i < table.Rows.Count; i++)
71 {
72 type[i] = ToScriptType(table.Rows[i]);
73 }
74 return type;
75 }
76
77 public ScriptTypeM[] Search(string sql, List<SQLiteParameter> parameterList)
78 {
79 DataTable table = SQLiteHelper.GetDataTable(sql, parameterList.ToArray());
80 ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];
81 for (int i = 0; i < table.Rows.Count; i++)
82 {
83 type[i] = ToScriptType(table.Rows[i]);
84 }
85 return type;
86 }
87 }

SQLite数据库小巧而且应用方便,在一些小型应用和嵌入式应用中很有优势,当然如何应用的得心应手就看个人了。


如果您希望更方便且及时的阅读相关文章,关注我的微信公众号【木南创智】




举报

相关推荐

0 条评论