在可移植类库 新建:
using SQLite.Net.Interop;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace CommonLib{ ////// 数据存储环境 /// public interface IDataStorage { ////// 存储路径 /// string StoragePath { get; } //////SQLite 平台环境 /// IOS: SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS /// Android: SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid ///... /// ISQLitePlatform SqlitePlatform { get; } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using SQLite.Net;namespace CommonLib{ ////// SQLite上下文 /// public class SQLiteContext { public SQLiteContext() { } private IDataStorage _dataStorage; ////// 构造上下文 /// /// 数据存储环境 public SQLiteContext(IDataStorage dataStorage) { _dataStorage = dataStorage; } ////// SQLite上下文 /// protected SQLiteContext Connection { get { return this; } } ////// 创建链接 /// ///public SQLiteConnection New() { if (_dataStorage == null) throw new ArgumentException("SQLiteContext构造时缺少IDataStorage对象实例!"); return new SQLite.Net.SQLiteConnection(_dataStorage.SqlitePlatform, _dataStorage.StoragePath); } }}
在xamarin.Android 工程内新建 SQLiteStorage.cs
////// 数据存储环境 /// public class SQLiteStorage : IDataStorage { ////// 存储路径 /// public string StoragePath { get { // 获取数据库文件存储路径 return System.IO.Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal), "db.db"); } } ////// SQLite 平台环境 /// Android: SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid /// IOS: SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS /// ... /// public SQLite.Net.Interop.ISQLitePlatform SqlitePlatform { get { return new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(); } } }
使用例子:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using SQLite.Net;using CommonLib;namespace BusinessLib{ ////// 涉及到操作SQLite时需要继承 ZsCMS.CommonLib.SQLiteContext /// public class TestSqlte: SQLiteContext { ////// /// /// 数据存储环境 public TestSqlte(IDataStorage dataStorage) : base(dataStorage)// 将UI层平台信息传入父类.创建当前平台的SQLite上下文 { } public void Insert(ZsCMS.ModelsLib.TestSqlte model) { // 通过父类Connection 创建数据链接 using (var conn= Connection.New()) { // 当表存在不会被创建,不存在表则创建 conn.CreateTable(); // 往表中添加数据 conn.Insert(model); } } public IEnumerable Gets() { using (var conn = Connection.New()) { // 查询数据列表 return conn.Query ("select * from TestSqlte"); } } }}