【Win 10 应用开发】Sqlite 数据库的简单用法

时间:2023-03-09 04:17:38
【Win 10 应用开发】Sqlite 数据库的简单用法

如果老周没记错的话,园子里曾经有朋友写过如何在 UWP 项目中使用 Sqlite数据库的文章。目前我们都是使用第三方封装的库,将来,SDK会加入对 Sqlite 的支持。

尽管目前 UWP-RT 库中还没有自带操作Sqlite数据库的API,不过,真要使用的话也不难,因为通过 Nuget ,我们其实可以获取很多支持 Sqlite 操作的第三方组件,当然了,组件虽多,但不是个个都好用,有的会发生这样那样的错误。老周试过几个库,找到一个比较不错的,而且支持 LINQ 操作。

其实呢,如果数据不是很多,老周认为用XML或JSON文件来存储可能更方便。

下面,老周分享一下这个封装库的用法,用起来也挺简单的。

1、在VS 中新建一个 UWP 应用项目。

2、在 解决方案资源管理器 窗口中的 引用 节点上右击,然后执行 管理NuGet程序包 菜单。

3、查找并安装以下两个组件:

【Win 10 应用开发】Sqlite 数据库的简单用法

-> SQLite.WUP.Native是必须安装的,它是封装sqlite操作函数的本地库,如果你用的是C++语言来开发,可以直接调用。如果不安装这个,在运行时会报找不到 sqlite3.dll 的错误。

-> SQLiteWrapperUWP-PCL也应该安装,它对sqlite的操作接口进行进一步封装,并且支持 LINQ 处理。

4、安装成功后,在引用列表会看到相关条目。

【Win 10 应用开发】Sqlite 数据库的简单用法

5、在代码中引入以下相关的命名空间。

using SQLite.Net;
using SQLite.Net.Attributes;
using SQLite.Net.Platform.WinRT;
using SQLite.Net.Interop;

6、要连接并创建表,要使用 SQLiteConnection 类,在构造实例时,用到两个必须的参数(其他参数可选):

sqlitePlatform:类型是 ISQLitePlatform 接口,它的实现类型是  SQLitePlatformWinRT ;

databasePath:数据库文件的路径,注意,由于UWP应用默认允许访问的路径不多,通常是本地目录。为了避免发生异常,可以通过 ApplicationData类来获取localFolder实例,然后从目录实例的 Path 属性得到本地目录的完整路径,再传递给该参数。

比如这样建立连接:

            string fdlocal = ApplicationData.Current.LocalFolder.Path;
string filename = "test.db";
string dbfullpath = Path.Combine(fdlocal, filename); ISQLitePlatform platform = new SQLitePlatformWinRT();
// 连接对象
SQLiteConnection conn = new SQLiteConnection(platform, dbfullpath);

当连接完不再需要时, 可以调用Dispose方法释放掉,或者干脆把连接的实例化放到一个 using 语句块中。

7、定义数据表模型,比如,我定义了一个 Student 类,它表示一张表。

    [Table("stu_info")]
public class Student
{
[Column("id")]
[PrimaryKey]
[AutoIncrement()]
public int ID { get; set; } [Column("name")]
[NotNull]
public string Name { get; set; } [Column("age")]
public int Age { get; set; }
}

对于要用于建表的类,要加上 Table 特性,对于属性,其实是映射到列,要加上Column特性。AutoImcrement特性表示字段的数值是自增长列。

8、创建表。实例化数据库连接后,可以调用连接对象的 CreateTable 方法直接创建表。

            ISQLitePlatform platform = new SQLitePlatformWinRT();
// 连接对象
SQLiteConnection conn = new SQLiteConnection(platform, dbfullpath);
WriteLine("db pathe: " + conn.DatabasePath); // 创建表
int rn = conn.CreateTable<Student>(CreateFlags.None);
WriteLine("create table res = {0}", rn); conn.Dispose();

CreateTable方法如果返回0,表明表创建无误。

9、插入数据。实例化连接对象后,访问 Insert 方法插入单条数据;InsertAll 方法插入多条数据;InsertOrReplace插入数据并替换已存在的记录;InsertOrReplaceAll 插入多条数据,并替换已存在项。

            using (SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), dbFullPath))
{
conn.DeleteAll<Student>();
// 插入数据
Student[] stus =
{
new Student { Name="小王",Age = },
new Student { Name = "小赵",Age= },
new Student {Name="小丁",Age= },
new Student {Name="小马",Age= }
};
int n = conn.InsertAll(stus);
WriteLine($"已插入 {n} 条数据。");

上面代码先用DeleteAll方法删除表中的所有记录,然后插入四条记录,插入方法返回已成功写入的记录数目,上面代码应返回 4 。

10、查询数据。可以用 LINQ 来查询。

            using (SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), dbFullpath))
{
// 获取列表
TableQuery<Student> t = conn.Table<Student>();
var q = from s in t.AsParallel<Student>()
orderby s.Age
select s;
// 绑定
lv.ItemsSource = q;
}

Table 方法返回一个 TableQuery实例,然后可以用 LINQ语句来处理。本例中筛选所有数据,并接照Age属性升序排列。

运行效果如下图所示。

【Win 10 应用开发】Sqlite 数据库的简单用法

好了,一个简单的演示就到这里了。怎么样,用起来不算难吧?有兴趣的话不妨研究研究。

示例源码下载地址