Windows 10 IoT Core 是微軟針對物聯網市場的一個重要產品,與以往的Windows版本不同,是為物聯網設備專門設計的,硬件也不僅僅限於x86架構,同時可以在ARM架構上運行。
前幾章我們講了 Raspberry 安裝 Win10 IoT 系統及搭建開發環境、部署程序及操作 GPIO 和 UART 的方法,通過這些功能我們已經可以獲得到傳感器發送給我們的數據,但是如果數據不能及時推送回服務器就需要在本地緩存,使用 SQLite 數據庫是一個不錯的選擇。這一章我們來看如何操作 IoT設備上的 SQLite數據庫。如果對安裝部署過程還不熟悉可以參考前幾篇文章,Raspberry安裝 IoT系統及搭建開發環境(http://www.cnblogs.com/cloudtech/p/5562120.html),創建 IoT應用及三種部署方法(http://www.cnblogs.com/cloudtech/p/5637983.html)。
准備工作:
刷好Win 10 IoT Core系統的 Raspberry Pi 2
部署Visual Studio 2015開發環境的PC
安裝sqlite3的PC
實驗目標:部署應用程序到 IoT設備,並在設備上創建 SQLite數據庫,進行 CURD操作。通過 FTP下載 IoT設備端的 SQLite數據庫,在PC端使用 sqlite3查看數據庫中的數據來驗證數據庫操作成功。
1.Visual Studio 2015 安裝 SQLite 擴展
打開 VS2015在 Tools 菜單中選擇 Extensions and Updates 菜單項。

為 VS2105安裝 SQLite的平台擴展,在搜索框中輸入sqlite查找,Search Results 中選擇 SQLite for Universal Windows Platform 進行下載安裝。

2.創建IoT項目並引用SQLite擴展
首先創建一個 Universal Windows應用程序,打開 VS 2015 點擊 New Project 在Visual C# -> Windows -> Universal 中找到 Blank App (Universal Windows) 項目模板,選中模板輸入項目名稱后點擊OK按鈕創建項目。

創建完成后為項目添加 SQLite平台擴展,右鍵選中項目點擊 Add Reference,在彈出窗口的樹視圖中選中 Universal Windows -> Extensions,列表中勾選 SQLite for Universal Windows Platform。

然后為項目添加 SQLite的類庫的引用,在 Tools菜單中選擇 NuGet Package Manager的 Manage NuGet Packages for Solution的菜單項。

在彈出的 NuGet界面中搜索 sqlitepcl,在搜索結果列表中選擇SQLitePCL,勾選右側項目列表中的 CloudTechIoT5,點擊 Install按鈕開始安裝。

3.編寫代碼
代碼工作流程:
首先在 IoT設備上創建名為 IoT5DB.sdf 的 SQLite數據庫文件,在數據庫中創建表 users,包含2個字段,id為主鍵 Integer類型自增長,name為text類型,向users表中插入三條數據,name字段值分別為 IoT-1、IoT-2、IoT-3。
然后更改第二條數據的name字段值為"IoT-dd-HH:mm:ss"格式,時間為當前時間。
最后刪除第一條數據。
完整代碼如下:
MainPage.xaml.cs
namespace CloudTechIot5
{
//http://www.cnblogs.com/cloudtech
//cloudtechesx@gmail.com
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
#region Fields
//數據庫名
private string _dbName;
//表名
private string _tableName;
//name字段的數據集合
private string[] _names = { "IoT-1", "IoT-2", "IoT-3" };
#endregion
#region Events
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Properties
private string _result;
//操作結果
public string Result
{
get
{
return _result;
}
set
{
_result = value;
OnPropertyChanged("Result");
}
}
#endregion
#region Constructor
public MainPage()
{
//初始化
_result = "Processing...";
_dbName = "IoT5DB.sdf";
_tableName = "users";
this.InitializeComponent();
//簡易MVVM框架
this.DataContext = this;
//創建數據庫連接
using (SQLiteConnection connection = CreateDbConnection())
{
//創建表
CreateTable(connection);
foreach (string name in _names)
{
//插入數據
InsertRow(connection, name);
}
//更新第二條數據
UpdateRow(connection, string.Format("IoT-{0}", DateTime.Now.ToString("dd-HH:mm:ss")), _names[1]);
//刪除第一條數據
DeleteRow(connection, _names[0]);
}
//更新界面
Result = "Completed...";
}
#endregion
#region Methods
private SQLiteConnection CreateDbConnection()
{
//創建連接
SQLiteConnection connection = new SQLiteConnection(_dbName);
if (null == connection)
{
throw new Exception("create db connection failed");
}
return connection;
}
private void CreateTable(SQLiteConnection connection)
{
//創建表
string sql = string.Format("create table if not exists {0} (id integer primary key autoincrement,name text)", _tableName);
using (ISQLiteStatement sqliteStatement = connection.Prepare(sql))
{
//執行語句
sqliteStatement.Step();
}
}
private void InsertRow(SQLiteConnection connection, string name)
{
//插入數據
string sql = string.Format("insert into {0} (name) values (?)", _tableName);
using (ISQLiteStatement sqliteStatement = connection.Prepare(sql))
{
//綁定參數
sqliteStatement.Bind(1, name);
//執行語句
sqliteStatement.Step();
}
}
private void UpdateRow(SQLiteConnection connection, string newName, string oldName)
{
string sql = string.Format("update {0} set name = ? where name = ?", _tableName);
using (ISQLiteStatement sqliteStatement = connection.Prepare(sql))
{
//綁定參數
sqliteStatement.Bind(1, newName);
sqliteStatement.Bind(2, oldName);
//執行語句
sqliteStatement.Step();
}
}
private void DeleteRow(SQLiteConnection connection, string name)
{
string sql = string.Format("delete from {0} where name = ?", _tableName);
using (ISQLiteStatement sqliteStatement = connection.Prepare(sql))
{
//綁定參數
sqliteStatement.Bind(1, name);
//執行語句
sqliteStatement.Step();
}
}
public void OnPropertyChanged(string propertyName)
{
//MVVM依賴屬性事件
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
MainPage.xaml
<Page
x:Class="CloudTechIot5.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CloudTechIot5"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="50"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
<Setter Property="Foreground" Value="Red"></Setter>
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
</Style>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical">
<TextBlock Text="cloudtechesx@gmail.com"/>
<TextBlock Text="{Binding Result, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"/>
</StackPanel>
</Grid>
4.部署應用
為Raspberry連接電源及網線,等待Windows 10 IoT 系統啟動完成。
在 Visual Studio 2015 的工具欄中選擇 Remote Machine 進行調試,IP地址輸入設備對應地址。點擊運行后應用自動部署到設備上。
![]()
應用部署完成后開始運行,顯示如下界面說明數據庫操作已執行完成。

5.驗證結果
關閉剛才部署的 IoT應用,Win10 IoT默認開啟 FTP服務,打開FTP客戶端連接IoT設備(這里使用的FTP客戶端是FileZilla),從 IoT設備如下位置下載生成的數據庫文件。
\Data\Users\DefaultAccount.MINWINPC\AppData\Local\Packages\{Package_Family_Name}\LocalState\{DbName}

Package Family Name在 Package.appxmanifest中查看。

在 SQLite官網 http://www.sqlite.org/download.html 下載 sqlite3 tools。
在 CMD中使用 sqlite3 tools 輸入命令 "sqlite3 IoT5DB.sdf" 打開下載的 SQLite 數據庫文件。
輸入SQL語句 "select * from users;" 查看表 users中的數據。

id為1的數據不存在。
id為2的數據name字段值為IoT-10-19:18:52。
id為3的數據name字段值為IoT-3。
數據庫中的數據與預期結果一致。
到這里C#操作 Win10 IoT設備本地 SQLite數據庫的過程就完成了,如果對代碼有優化的建議,歡迎留言或發郵件給我(cloudtechesx@gmail.com)。也可以掃描下面的二維碼加我的微信號查看以前的文章。
項目源碼 GitHub https://github.com/CloudTechx/CloudTechIot 的 CloudTechIot5 目錄下。
Win10 IoT C#開發 1 - Raspberry安裝IoT系統及搭建開發環境 http://www.cnblogs.com/cloudtech/p/5562120.html
Win10 IoT C#開發 2 - 創建基於XAML的UI程序 及 應用的三種部署方法 http://www.cnblogs.com/cloudtech/p/5637983.html
Win10 IoT C#開發 3 - GPIO Pin 控制發光二極管 http://www.cnblogs.com/cloudtech/p/5617902.html
Win10 IoT C#開發 4 - UART 串口通信 http://www.cnblogs.com/cloudtech/p/5518306.html

