Xamarin.Forms中SQLite.Net的使用

Xamarin.Forms中SQLite.Net的使用

最近有朋友问Xamarin中怎么使用Sqlite,所以在这里简单讲讲在安装Sqlite.net后使用时必须解决的问题,Sqlite的具体使用不讲。

 首先,通过nuget包管理器安装Sqlite.Net包。

然后,需要一个类来创建连接数据库,这个类需要继承自SQLiteConnection。

public class DataBase : SQLiteConnection
    {
        public DataBase(ISQLitePlatform platform, string dbfilePath):base(platform,dbfilePath)
        {

        }
    }
  1. dbfilePath不多说,就是数据库的地址。
  2. platform这里需要说明:
  • iOS中设置 platform = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
  • UWP中设置 platform = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
  • Android在这里需要特别说明一下:
    • 在AndroidN即(7.0)以下版本设置 platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
    • 在AndroidN以上设置platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroidN();

这里会发现没有这个类,这个类需要单独安装扩展包。如果直接从nuget包管理器下载是无法安装的,因为兼容性的问题。可以从nuget官网去下载,解压后导入dll即可。

SQLite.Net.Platform.XamarinAndroidN:https://www.nuget.org/packages/SQLite.Net.Platform.XamarinAndroidN

        

public ISQLitePlatform GetSQLitePlatform()
        {
            if(Build.VERSION.SdkInt >= Build.VERSION_CODES.N)
            {
                return new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroidN();
            }
            else
            {
                return new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
            }
        }

到这里,ios、UWP中数据库可以正常使用了,但是Android还会报错(Unhandled Exception: System.DllNotFoundException: libsqlite3_xamarin),这是为什么呢?

官方文档这样说的:

https://developer.xamarin.com/releases/android/xamarin.android_6/xamarin.android_6.0/

Due to a change by Google, Android N will now only permit linking to NDK-provided native librarieslibsqlite.so is not an NDK-provided native library. Consequently, existing apps using e.g. Mono.Data.Sqlite.dll will crash when running on Android N. This may include other SQLite-using assemblies, not distributed with Xamarin.Android.

在andorid7.0后,不允许应用调用系统的sqlite,所以需要应用自己引入。

这时我们需要在Android项目中安装Mono.Data.Sqlite.Portable(nuget中直接下载即可),这样Android中也可以使用Sqlite了。

猜你喜欢

转载自www.cnblogs.com/devin_zhou/p/9243087.html