wp8.1 SQLite的基本使用

SQLite是一个轻量级的关系型数据库,正是由于其精悍小巧,在移动端平台被广泛应用,但不适合处理大量数据和批量操作。它的底层是由C语言编写,最初设计是为了应用于嵌入式,占用资源非常低且简单易用,而且绝大部分程序语言都可以很好的与之结合。在.net中它的sdk中支持linq实现方式,使用更加方便。

sdk安装。

安装好了之后,我们引用dll。

这时候出现这样的错误,这是由于sdk只支持arm和32位的编译环境。

4

可以将通过项目属性将平台目标选为32位。

这里要说明一下,sqlite for wp8.1 sdk适用于32位和winrt,调试的时候可以选为32位,编译发布的时候,wp只能识别这个arm平台的环境。否则会报出 Error - Deployment optimization failed due to an assembly that's not valid. Try rebuilding the project, and then try again.

4

接下来还需要安装sqlite-net,可以这行package console的shell命令。

2

这时候我们的项目中会出现两个cs文件。

1

接下来我们来验证一下sdk,首先创建一个表对象。

 1 using System;
 2 using SQLite;
 3 
 4 namespace FY.Weather.DataModel
 5 {
 6     [Table("Temp")]
 7     public class Temp
 8     {
 9         [PrimaryKey, AutoIncrement]
10         public int Id { get; set; }
11 
12         public string JsonData { get; set; }
13 
14         public DateTime CreationDate { get; set; }
15     }
16 }

调用sdk创建表。

1 private async void CreateTemp()
2 {
3     string dbName = ViewModelLocator.Instance.DBName;
4     if (!await Common.CheckFileAsync(dbName))
5     {
6         SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection(dbName);
7         await conn.CreateTableAsync<Temp>();
8     }
9 }

 获取表数据。

 1 private async System.Threading.Tasks.Task<Temp> GetTemp(int id)
 2 {
 3     SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection(ViewModelLocator.Instance.DBName);
 4     var query = await conn.QueryAsync<Temp>("select * from temp where id=?", new object[] { id });
 5     if (query != null && query.Count > 0)
 6     {
 7         return query[0];
 8     }
 9     return null;
10 }

添加修改数据。

 1 private async void AddOrEditTemp(Temp temp)
 2 {
 3     SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection(ViewModelLocator.Instance.DBName);
 4     var query = await conn.QueryAsync<Temp>("select * from temp where id=?", new object[] { temp.Id });
 5     if (query != null && query.Count > 0)
 6     {
 7         await conn.UpdateAsync(temp);
 8     }
 9     else
10     {
11         await conn.InsertAsync(temp);
12     }
13 }

验证数据库文件是否存在。

 1 public static async System.Threading.Tasks.Task<bool> CheckFileAsync(string fileName)
 2 {
 3     bool fileIsExist = true;
 4     try
 5     {
 6         Windows.Storage.StorageFile sf = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
 7     }
 8     catch
 9     {
10         fileIsExist = false;
11     }
12     return fileIsExist;
13 }
原文地址:https://www.cnblogs.com/yuefei/p/3873610.html