Win10 IoT C#开发 5 - 操做 IoT 设备内嵌 SQLite 数据库 CURD

Windows 10 IoT Core 是微软针对物联网市场的一个重要产品,与以往的Windows版本不一样,是为物联网设备专门设计的,硬件也不单单限于x86架构,同时能够在ARM架构上运行。html

前几章咱们讲了 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)。git

 

准备工做:github

刷好Win 10 IoT Core系统的 Raspberry Pi 2sql

部署Visual Studio 2015开发环境的PC数据库

安装sqlite3的PCexpress

 

实验目标:部署应用程序到 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-一、IoT-二、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

相关文章
相关标签/搜索