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

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

posted @ 2016-07-10 20:09  CloudTech  阅读(3486)  评论(4编辑  收藏  举报