Microsoft Open Technologies has recently released a Portable Class Library for SQLite. Thanks to it, we can use SQLite in the same way in all the supported platforms. Let’s see how to do that.

As prerequisite, we need to install the SQLite Extension SDK that corresponds to our platform. For example, for Windows 8.1, it is the SQLite for Windows Runtime (Windows 8.1) v3.8.2 extension SDK. The other versions are available on the SQLite official download page. Once downloaded, it’s necessary to change the extension from ZIP to VSIX, then double click it to install the SDK. Now we can add the extension to the project using the Add reference command:

SQLite for Windows Runtime

Because it is a native library, the “Any CPU” architecture is not supported, so we need to choose a specific target platform: Visual studio will reference the appropriate extension SDK version the the project compiles.

Finally, let’s use NuGet to install the Portable Class Library for SQLite:

SQLitePCL on NuGet

Now everything is ready to start using the library. Suppose for example we want to create a database named Storage.db with a People table:

1
2
3
4
5
6
7
8
9
10
using (var connection = new SQLiteConnection("Storage.db"))
{
    using (var statement = connection.Prepare(@"CREATE TABLE IF NOT EXISTS People (
                                                ID INTEGER NOT NULL PRIMARY KEY,
                                                FirstName NVARCHAR(50),
                                                LastName NVARCHUAR(50));"))
    {
        statement.Step();
    }
}

First of all, we create an SQLiteConnection object that points to the specified file. If it isn’t rooted, the library assumes that it is located in the ApplicationData.Current.LocalFolder folder (the same assumption applies also for Windows Phone 8).

At this moment, SQLite PCL supports only direct SQL commands (no LINQ provider). At line 3, we use the connection.Prepare method to define the DDL query we want to execute. Then, on line 8, with statement.Step, we send the query to the database engine, that immediately executes it.

The following example shows how to insert data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using (var statement = connection.Prepare(@"INSERT INTO People (FirstName, LastName)
                                            VALUES(@firstName, @lastName);"))
{
    statement.Bind("@firstName", "Donald");
    statement.Bind("@lastName", "Duck");
 
    // Inserts data.
    statement.Step();
 
    // Resets the statement, to that it can be used again (with different parameters).
    statement.Reset();
    statement.ClearBindings();
 
    statement.Bind("@firstName", "Mickey");
    statement.Bind("@lastName", "Mouse");
 
    // Inserts data.
    statement.Step();
}

Again, the Prepare method is used to define the SQL command. In this case, it is an INSERT in which we have defined two parameters, @firstName and @lastName. At line 4-5, we bind them to their actual values, using the Bind method. The Step command (line 8) finalizes the operation.

Then, because we want to reuse the same statement to insert another record, we need to call Reset (line 11), that resets the prepared statement back to its initial state, ready to be re-executed, and ClearBindings (line 12), to remove the bindings that have been defined before.

Finally, it’s the moment to retrieve the saved data:

1
2
3
4
5
6
7
8
9
using (var statement = connection.Prepare(@"SELECT * FROM People ORDER BY FirstName;"))
{
    while (statement.Step() == SQLiteResult.ROW)
    {
        var id = (long)statement[0];
        var firstName = (string)statement[1];
        var lastName = (string)statement[2];
    }
}

To read the records returned by the query, we need to iterate through the rows, in a way that resembles the SqlDataReader.Read method.

In order to retrieve the actual values, we need to use the indexer operator on the statement object, specifying the column number. As this method gets a result of Object type, we need to cast it to the real type of the column. If we want to avoid this syntax, and instead prefer to use generics, we can define a simple extension method:

1
2
3
4
5
6
7
public static class SQLitePCLExtensions
{
    public static T GetValue<T>(this ISQLiteStatement statement, int index)
    {
        return (T)statement[index];
    }
}

And so in the previous loop we can write:

1
2
3
var id = statement.GetValue<long>(0);
var firstName = statement.GetValue<string>(1);
var lastName = statement.GetValue<string>(2);

As we have seen, this library is very straightforward. Its usage mimics the native C++ library (the Prepare, Step and Reset methods, for example), with a great advantage: we can code against one single API, regardless of whether we’re developing Windows Store, Windows Phone or .NET 4.5 projects.

More information about the Portable Class Library for SQLite are available on CodePlex.

The new Portable Class Library for SQLite z的更多相关文章

  1. 使用 Portable Class Library(可移植类库)开发 Universal Windows App

    今天在这里跟大家聊聊关于 Windows Universal 应用夸平台的问题,首先Universal Windows App的定义相信大家已经有所了解了(如果你是一个刚刚接触 Universal A ...

  2. Architecture of SQLite

    Introduction This document describes the architecture of the SQLite library. The information here is ...

  3. How to Make Portable Class Libraries Work for You

    A Portable Class Library is a .NET library that can be used (in binary form, without recompiling) on ...

  4. 【Android】13.0 第13章 创建和访问SQLite数据库—本章示例主界面

    分类:C#.Android.VS2015: 创建日期:2016-02-26 一.简介 Android 内置了三种数据存取方式:SQLite数据库.文件.SharedPreferences. 这一章我们 ...

  5. C++ Development Library

    C/C++ 开发库 | C/C++ Development Library 这里收集一些著名的 C/C++ 开发库.SDK.类库.可复用类与结构代码 等信息,列举它们的介绍.参考和网站链接,为各位 C ...

  6. Inside Portable Class Libraries

    Portable Class Libraries were introduced with Visual Studio 2010 SP1 to aid writing libraries that c ...

  7. Prism5.0新内容 What's New in Prism Library 5.0 for WPF(英汉对照版)

    Prism 5.0 includes guidance in several new areas, resulting in new code in the Prism Library for WPF ...

  8. 下载并安装Prism5.0库 Download and Setup Prism Library 5.0 for WPF(英汉对照版)

    Learn what’s included in Prism 5.0 including the documentation, WPF code samples, and libraries. Add ...

  9. C++开源库集合

    | Main | Site Index | Download | mimetic A free/GPL C++ MIME Library mimetic is a free/GPL Email lib ...

随机推荐

  1. 由于本公司项目需要,现急需拥有微软MCSE证书的人才,一经录用,待遇从优!

    志鸿科技于1988年在香港创办,从事资讯科技服务,为本地及跨国金融企业提供各种合适的企业应用软件及方案,并于2000年6月30日在香港联合交易所创业板成功上市 (股票代号8048),香港长江实业.新加 ...

  2. 对象工具类 - ObjectUtils.java

    对象工具类,提供对象克隆.获取对象属性.类型判断.Map转换对象.对象转Map.设置对象属性等. 源码如下:(点击下载 -  ObjectUtils.java .JsonUtils.java .gso ...

  3. Machine Learning for Developers

    Machine Learning for Developers Most developers these days have heard of machine learning, but when ...

  4. PAT-乙级-1043. 输出PATest(20)

    1043. 输出PATest(20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 给定一个长度不超过10000 ...

  5. FaceNet--Google的人脸识别(转)

    引入 随着深度学习的出现,CV领域突破很多,甚至掀起了一股CV界的创业浪潮,当次风口浪尖之时,Google岂能缺席.特贡献出FaceNet再次刷新LFW上人脸验证的效果记录. 本文是阅读FaceNet ...

  6. ppshu

    全部书籍已经下载完毕! http://3cvpkfx4gdnkcduj.onion/ https://3cvpkfx4gdnkcduj.onion.cab/ https://3cvpkfx4gdnkc ...

  7. JSP中脚本、声明和表达式的本质区别

     JSP脚本元素 使用JSP脚本元素可以将Java代码嵌入到JSP页面里,这些Java代码将出现在由当前JSP页面生成的Servlet中,使JSP将静态内容与动态内容分离出来.脚本元素包含:  1. ...

  8. 对JAVA动态代理的理解

    叫动态代理就代表着有“静态代理”这回事. 而且,通常“动态”至少听着更NB一点. 关键就在于不明白啥叫“动”,这个得跟“静”比较下. 在我的理解,静态代理得自己声明一个类,实现跟被代理对象同样的接口. ...

  9. PreparedStatement是如何大幅度提高性能的

    本文讲述了如何正确的使用prepared statements.为什么它可以让你的应用程序运行的更快,和同样的让数据库操作变的更快.  为什么Prepared Statements非常重要?如何正确的 ...

  10. Android:@id和@+id

    @id代表引用已有的id,而@+id是新增加一个id 如果使用@+id/name形式,当R.java中存在名为name变量时,则该组件会使用该变量的值作为标识.如果不存在该变量,则添加一个新的变量,并 ...