Xamarin.Forms<五> Android的本地数据库SQLite

1、准备工作:
在项目的“管理NuGet程序包”中安装“SQLite.Net PCL”和“SQLite.Net PCL - XamarinAndroid Platform”
在引用中“添加引用”添加SQLite.Net.dll以及SQLite.Net.Platform.XamarinAndroid.dll。

2、在Common项目的Tables文件夹下创建映射类(SQLite表),这个类的结构完全是对应到SQLite数据库中的表。
创建一个名为t_Custom表

 1 public class t_Custom
 2     {
 3         /// <summary>
 4         ///id
 5         /// </summary>
 6         [PrimaryKey, AutoIncrement]
 7         public int Id{ get; set; }
 8 
 9         /// <summary>
10         ///客户名称
11         /// </summary>
12         public string CustomName { get; set; }
13     }
View Code

[PrimaryKey]:表示该表的主键,只能用于Int类型的属性。

[AutoIncrement]:用于需要自增的属性,每插入一条新数据该字段都会自增,只能用于Int类型。

[Column(name)]:用来表示指定属性对应到表中字段的名称,如果不加该属性则表中的字段名与属性名相同。

[Table(name)]:用来表示指定类对应到数据库中的表名称,如果不加该属性则数据库中的表名称与该类名称相同。

[MaxLength(value)]:用来限制字段能够保存的最长字符长度。

[Ignore]:表示忽略该属性,从而不会在表中生成对应的字段。

[Unique]:表示该属性的值必须在表中唯一。

3、打开SQLite数据库
需要在android项目下建立一个SQLite的类,名为SQLite_Android
编写对SQLite的联系方法:GetConnection();
打开该数据库。如果不存在该数据库,则会自动创建该文件。在为止我们仅仅创建了一个空的数据库,里面还不存在任何表。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using Xamarin.Forms;
 6 using System.IO;
 7 using Test.Mobile.Common;
 8 using SQLite.Net;
 9 using Test.Mobile.Droid;
10 
11 [assembly: Dependency(typeof(SQLite_Android))]
12 
13 namespace Autoloan.Mobile.Droid
14 {
15     public class SQLite_Android : ISQLite
16     {
17         public SQLite_Android()
18         {      
19         }
20 
21         /// <summary>
22         /// 连接SQLite
23         /// </summary>
24         /// <returns></returns>
25         public SQLite.Net.SQLiteConnection GetConnection()
26         {
27             try
28             {
29                 //SQLite文件的名称
30                 var sqliteFilename = "TodoSQLite.db3";
31                 //将SQLite保存在自定义的文件夹下,文件夹不存在则新建
32                 string documentsPath = System.Environment.GetFolderPath
33 
34 (System.Environment.SpecialFolder.Personal);
35                 var path = Path.Combine(documentsPath, sqliteFilename);
36                 var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
37                 var conn = new SQLite.Net.SQLiteConnection(plat, path);
38 
39                 // Return the database connection 
40                 return conn;
41             }
42             catch(Exception ex)
43             {
44             }
45         }       
46     }
47 }
View Code

在命名空间Test.Mobile.Common下的ISQLite接口

1 namespace Test.Mobile.Common
2 {
3     public interface ISQLite
4     {
5         SQLiteConnection GetConnection();
6     }
7 }
View Code

4、表的操作
创建表

db.CreateTable<Custom>();
或者下面这个方式也一样可以:
db.CreateTable(typeof(Custom));

 1         /// <summary>
 2         /// 创建sqlite数据库相关表
 3         /// </summary>
 4         /// <param></param>
 5         /// <returns></returns>
 6         public bool CreateDBTables()
 7         {
 8             try
 9             {
10                 using (SQLiteConnectiondb = new SQLiteConnection())
11                 {
12                     db.CreateTable<t_Custom>();
13                 }
14                 return true;
15             }
16             catch (Exception ex)
17             {
18                 return false;
19             }
20         }
View Code

注:实际运用中一定会有人想找如何判断该表是否已经创建的方法,其实没有必须要找,即使重复的执行该操作,也不会影响什么,表一旦创建之后再执行就不会重新创建了。

5、数据的操作
插入数据

 1         /// <summary>
 2         /// 新增客户
 3         /// </summary>
 4         /// <returns></returns>
 5         public bool AddCustom(t_Custom _custom)
 6         {
 7             try
 8             {
 9                 using (SQLiteConnectiondb = new SQLiteConnection())
10                 {
11                     db.RunInTransaction(() =>
12                     {
13                         //添加客户
14                         db.Insert<t_Custom>(_custom);
15                     });
16                 }
17                 return true;
18             }
19             catch (Exception ex)
20             {
21                 return false;
22             }
23         }    
View Code

获得数据

 1         /// <summary>
 2         /// 查询客户
 3         /// </summary>
 4         /// <returns></returns>
 5         public t_Custom GetCustom(int _customId)
 6         {
 7             try
 8             {
 9                 using (SQLiteConnection db = new SQLiteConnection())
10                 {
11                        var q = db.Get<t_Custom>(x=>x.Id == _customId).FirstOrDefault();
12                        return q;
13                 }
14             }
15             catch (Exception ex)
16             {
17                 return false;
18             }
19         }        
View Code

更新数据

 1         /// <summary>
 2         /// 跟新客户
 3         /// </summary>
 4         /// <returns></returns>
 5         public bool UpdateCustom(t_Custom _custom)
 6         {
 7             try
 8             {
 9                 using (SQLiteConnection db = new SQLiteConnection())
10                 {
11                        var q = db.Get<t_Custom>(x=>x.Id == _custom.Id).FirstOrDefault();
12                         q.CustomName = _custom.CustomName;
13                        db.Update<t_Custom>(q);
14                        return true;
15                 }
16             }
17             catch (Exception ex)
18             {
19                 return false;
20             }
21         } 
22 
23 
24         
View Code

删除数据

1 db.Delete<t_Custom>(_custom.Id);
View Code

一下是几个不错的文章,可以参考

Y-Z-F的一篇关于SQLite的文章

http://www.cnblogs.com/yaozhenfa/p/xamarin_android_sqlite_net_orm.html

Xamarin.Forms的SQLite网址
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/databases/#Adding_SQLite_to_WinPhone

SQLite 系统升级,数据库数据存在
http://blog.csdn.net/lucky_liuxiang/article/details/38656769

Android五中存储方式
http://www.cnblogs.com/hanyonglu/archive/2012/03/01/2374894.html

原文地址:https://www.cnblogs.com/shadow-fei/p/4179619.html