MVP可以在channel 9上传视频了,所以准备做个英文视频传上去分享给大家,本文做稿子。

Hello everyone,

As we all know, SQLite is a great and popular local database running on mobile devices. Consider of its powerful and useful features, lots of apps use SQLite database as the main way of application data storage, including Android and iOS apps. What's more, SQLite is a cross-platform database and also have windows version so that windows apps are easy to integrate with it. Today I will give a lesson about using SQLite in UWP project.

Install

Firstly, it's necessary for us to install SQLite for windows. you can download the binary install file here. Actually, you can alse download the source and build it by youself, if you like source more. After you finnished installation, you can find the sqlite extension in the refrence window. It will look like this:

And we need to add the VC++ 2015 Runtime refrence too.

 Project Configuration

Secondly, we need to add a framework named SQLite.Net for using SQLite effectively. In other words, SQLite.Net libary will help us access sqlite database more esaily. It have some relese versions which you can find in NuGet, and two of them are most useful, including SQLite.Net-PCL and SQLite.Net.Async-PCL.

What's the defference between SQLite.Net-PCL and SQLite.Net.Async-PCL framework is that SQLite.Net.Async-PCL support asynchronous operations. Actually I like async-await more, so I will install SQLite.Net.Async-PCL framework. Once we finish configurations, we can write some code to use SQLite now.

SQLiteDBManager

Let's we have some interesting codes to begin using this amazing tool now. What's more, I will provide some example codes written by myself for you. The mainly code is used to manager local SQLite database file and access it more easily, so I named it SQLiteDBMnager.

Before we access the data of database, we need import and manage the database file. In windows runtime framework we need to move or create database file in ApplicationData folder. And you can create a database file using SQLite Expert which is famous manage tool for SQLite database.

/// <summary>
/// init db
/// </summary>
private static async void InitDBAsync()
{
try
{
var file = await ApplicationData.Current.LocalFolder.TryGetItemAsync("ysy.sqlite");
if (file == null)
{
var dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Data/ysy.sqlite"));
file = await dbFile.CopyAsync(ApplicationData.Current.LocalFolder);
var dbConnect = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), new SQLiteConnectionString(file.Path, true)));
//create db tables
var result = await dbConnect.CreateTablesAsync(new Type[] { typeof(Product), typeof(P2PData), typeof(ProductDetail), typeof(P2PDataDetail), typeof(ProductExtend), typeof(P2PDataExtend) });
Debug.WriteLine(result);
} }
catch (Exception ex)
{
Debug.WriteLine(ex.Message); }
}

After we initialize database, we need to access the data of database. Fortunately, SQLite.NET provides some method for us, but we still do some works to simplify codes.

/// <summary>
/// get current DBConnection
/// </summary>
/// <returns></returns>
public async Task<SQLiteAsyncConnection> GetDbConnectionAsync()
{
if (dbConnection == null)
{
var path = await GetDBPathAsync();
dbConnection = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), new SQLiteConnectionString(path, true)));
}
return dbConnection;
}

Add/Delete/Modify/Find

/// <summary>
/// insert a item
/// </summary>
/// <param name="item">item</param>
/// <returns></returns>
public async Task<int> InsertAsync(object item)
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.InsertOrReplaceAsync(item);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return -;
} } /// <summary>
/// insert lots of items
/// </summary>
/// <param name="items">items</param>
/// <returns></returns>
public async Task<int> InsertAsync(IEnumerable items)
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.InsertOrReplaceAllAsync(items);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return -;
} } /// <summary>
/// find a item in database
/// </summary>
/// <typeparam name="T">type of item</typeparam>
/// <param name="pk">item</param>
/// <returns></returns>
public async Task<T> FindAsync<T>(T pk) where T : class
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.FindAsync<T>(pk);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
} /// <summary>
/// find a collection of items
/// </summary>
/// <typeparam name="T">type of item</typeparam>
/// <param name="sql">sql command</param>
/// <param name="parameters">sql command parameters</param>
/// <returns></returns>
public async Task<List<T>> FindAsync<T>(string sql, object[] parameters) where T : class
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.QueryAsync<T>(sql, parameters);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
} /// <summary>
/// update item in table
/// </summary>
/// <typeparam name="T">type of item</typeparam>
/// <param name="item">item</param>
/// <returns></returns>
public async Task<int> UpdateAsync<T>(T item) where T : class
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.UpdateAsync(item);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return -;
}
} /// <summary>
/// update lots of items in table
/// </summary>
/// <typeparam name="T">type of item</typeparam>
/// <param name="items">items</param>
/// <returns></returns>
public async Task<int> UpdateAsync<T>(IEnumerable items) where T : class
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.UpdateAllAsync(items);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return -;
}
}
/// <summary>
/// delete data from table
/// </summary>
/// <typeparam name="T">type of item</typeparam>
/// <param name="item">item</param>
/// <returns></returns>
public async Task<int> DeleteAsync<T>(T item) where T : class
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.DeleteAsync<T>(item);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return -;
}
} /// <summary>
/// delete all items in table
/// </summary>
/// <param name="t">type of item</param>
/// <returns></returns>
public async Task<int> DeleteAsync(Type t)
{
try
{
var dbConnect = await GetDbConnectionAsync();
return await dbConnect.DeleteAllAsync(t);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return -;
}
}

Last but not least, we can access the database easily. For example,

 /// <summary>
/// get product tabele data
/// </summary>
/// <returns></returns>
private async Task<List<Fund>> GetFundDataFromDataBaseAsync()
{
var manager = SQLiteDBManager.Instance();
var funds =new List<Fund>();
var products = await manager.FindAsync<Product>("select * from Product", null);
products.ForEach(p => {
funds.Add(new Fund { Id=p.ProductId.ToString(), Host=p.Company, Image=p.Icon, Name=p.Name, Platform=p.FoundationName, QRNH=p.QRNH, WFSY=p.WFSY });
});
if (funds != null && funds.Count > )
{
return funds;
}
return null;
}

You can get entire file here.

Conclusion

SQLite database is a good choice as application data storage container, and more excellent that ApplicationSettings and Xml/Json data files in many ways, I think.

Using SQLite database in your Windows 10 apps的更多相关文章

  1. Always run a program in administrator mode in Windows 10

    From: https://www.cnet.com/how-to/always-run-a-program-in-administrator-mode-in-windows-10/ If you'r ...

  2. SQLite.Net-PCLUSING SQLITE IN WINDOWS 10 UNIVERSAL APPS

    USING SQLITE IN WINDOWS 10 UNIVERSAL APPS 1.下载SQLite VSIX package并安装 http://sqlite.org/download.html ...

  3. SQLite in Windows Store Apps

    Using SQLite in Windows Store Apps : https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Using-SQL ...

  4. Build better apps: Windows 10 by 10 development series

    http://blogs.windows.com/buildingapps/2015/08/05/build-better-apps-windows-10-by-10-development-seri ...

  5. UWP深入学习六:Build better apps: Windows 10 by 10 development series

    Promotion in the Windows Store  In this article, I walk through how to Give your Store listing a mak ...

  6. New Windows 10 SDK - Multi-instance UWP apps

    概述 前面一篇 About Windows 10 SDK Preview Build 17110 中,我们简单介绍了 Multi-instance UWP Apps,今天结合开发过程详细讲解一下. 在 ...

  7. Building Apps for Windows 10 on LattePanda–Jump Start

    1.引言 目前来看,LattePanda应该是最小的运行Full Windows 10系统的开发板了(注意,不是Windows 10 for Mobile,也不是Windows 10 IoT系列,而是 ...

  8. DB 查询分析器 6.04 在 Windows 10 上的安装与运行展示

    DB查询分析器 6.04 在 Windows 10 上的安装与运行展示 中国本土程序员马根峰(CSDN专访马根峰:海量数据处理与分析大师的中国本土程序员 http://www.csdn.net/art ...

  9. 【本人译作推荐】Windows 8应用开发:C#和XAML卷(原名:Building Windows 8 Apps with C# and XAML)

    [图书推荐] 译名:Windows 8应用开发:C#和XAML卷 原名:Building Windows 8 Apps with C# and XAML   编辑推荐 国内第一本使用XAML与C#语言 ...

随机推荐

  1. Codeforces Round #437 C. Ordering Pizza

    题意: n个人吃披萨,总共有两种披萨,每种披萨都是有S块,给出每个人要吃的块数,吃第一种披萨能获得的happy值,吃第二种披萨能获得的happy值,问你,在购买的披萨数最少的情况下能获得的最大的总的h ...

  2. python 迭代多个对象

    并行迭代 zip for a,b,c in zip(list,list,tuple,list): print a,b,c 串行迭代 itertools.chain a = [1,2,3,4,5] b ...

  3. 【Django】django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.

    最近学习Django的过程中,在cmd打算使用python manage.py shell来测试数据的时候,当我一导入自己写的model类,就发现报了这个错误django.core.exception ...

  4. oracle函数nvl, nvl2, nullif

    nvl函数 语法: NVL(表达式1, 表达式2) select nvl(s.name, '未填写') from student s 如果表达式1的值为空, 则显示第二个值, 否则显示原来的值, nv ...

  5. Windows server 2012 R2 解决“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同

    Windows server 2012 R2 解决“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同.”使用克隆的系统时,加域是出现如下问题.“无法完成域加入,原因是试图加入的域的SI ...

  6. Java的三种代理模式(Spring动态代理对象)

    Java的三种代理模式 1.代理模式 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩 ...

  7. oracle 中的sql 语句

    1.update 表名 set 表字段=(select 另一个表中的相同字段 from 另一个表表名 where 表.字段=另一个表.字段) where  表.字段=? 例子:将某个表中的更新到另一个 ...

  8. vue 前端框架 目录

    vue 前端框架 目录   vue-目录 ES6基础语法 vue基础语法 Vue.js的组件化思想 —上 Vue.js的组件化思想 —下 Vue + Vue-Router结合开发 SublimeSer ...

  9. gdb调试技巧 找到php执行进程当前执行的代码

    假设线上有一段php脚本,突然在某天出问题了,不处理但是进程没有退出.这种情况可能是异常休眠或者是有段死循环代码,但是我们怎么定位呢,我们这个时候最想知道的应该是这个脚本在此刻在做什么吧.这个是gdb ...

  10. Fefora 14 源

    默认的源不能用,需要用下边的源路径. [fedora] name=Fedora $releasever - $basearch failovermethod=priority #baseurl=htt ...