【问题标题】:Xamarin: How to use existing databaseXamarin:如何使用现有数据库
【发布时间】:2020-03-29 02:14:09
【问题描述】:

我正在尝试在我的应用程序中使用现有的 sqlite 数据库。不知道该怎么做。 我在网上看到了一些建议,但没有发现任何有用的建议。

【问题讨论】:

  • 定义现有数据库。就像您的应用资源内部的一个或事先存在于设备上的一个。
  • 您在项目中包含 db 文件,在应用启动时需要将其复制到可写文件夹。
  • HSchmale:数据库在资产/资源中。
  • Jason:我是 Xamarin 新手,不知道如何将 db 文件从资产/资源复制到设备文件夹。你能提供任何代码示例吗?

标签: sqlite xamarin


【解决方案1】:

根据您的描述,您在Android项目的Assest中添加了一个sqlite数据库,现在您想使用这个sqlite。

首先,在所有三个PCL、Android和IOS项目中安装Sqlite.net.core,在Android项目中安装SQLite.Net.Platform.XamarinAndroid。

然后在 PCL 中创建接口 IDatabase.cs:

 public interface IDatabase
{
    SQLite.Net.SQLiteConnection createconnection();
}

在Android中实现该接口获取SqliteConnection。

public class GetDatabase : IDatabase
{
    public SQLite.Net.SQLiteConnection createconnection()
    {
        var fileName = "SQLite.db3";
        var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var path = Path.Combine(documentPath, fileName);

        if(!File.Exists(path))
        {
            using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(fileName)))
            {
                using (BinaryWriter bw = new BinaryWriter(new FileStream(path, FileMode.Create)))
                {
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        bw.Write(buffer, 0, len);
                    }
                }
            }
        }

        var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
        var conn = new SQLite.Net.SQLiteConnection(plat, path);

        return conn;
        //var plat = new SQLite.Net.Plataform.XamarinAndroid.SqlitePlatformAndroid();



    }

请注意:SQLite.Net.Platform.XamarinAndroid早期版本安装成功。但是,它会抛出错误“Package SQLite.Net.Platform.XamarinAndroidN 3.1.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0)”并且包安装会失败。这是一个错误,今天没有解决方案。你可以从this link复制这个dll来添加你的android项目。

更多详细信息,请看:

Use a local database in Xamarin

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2013-06-03
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多