【问题标题】:Using SQLite database in Xamarin.Forms在 Xamarin.Forms 中使用 SQLite 数据库
【发布时间】:2017-09-25 15:26:54
【问题描述】:

我已经创建了一个 SQLite 数据库(使用 cmd shell sqlite3.exe),现在正尝试使用此页面 https://developer.xamarin.com/guides/android/application_fundamentals/data/part_3_using_sqlite_orm/ 作为指导在 Xamarin.Forms 中实现它。不过,我很困惑,因为我不知道数据库的路径是什么。我将数据库命名为“app”,将表命名为“tbl1”,但这就是我所知道的所有信息。该数据库仅存储用户名和密码,仅用于我的跨平台应用程序的登录页面。

【问题讨论】:

标签: c# xamarin sqlite xamarin.forms


【解决方案1】:

使用Xamarin.Forms(您的链接适用于Android!),您必须使用共享项目中的某种抽象来访问您的数据库(这是特定于平台的)。这就是您基本上可以获得每个平台的正确存储路径的方法。

这基本上意味着在共享项目中创建一个接口,即:

public interface IFileHelper
{
  string GetLocalFilePath(string filename);
}

然后,您必须实现平台特定的部分。即安卓:

[assembly: Dependency(typeof(FileHelper))]
namespace Todo.Droid
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string filename)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            return Path.Combine(path, filename);
        }
    }
}

iOS:

[assembly: Dependency(typeof(FileHelper))]
namespace Todo.iOS
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string filename)
        {
            string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");

            if (!Directory.Exists(libFolder))
            {
                Directory.CreateDirectory(libFolder);
            }

            return Path.Combine(libFolder, filename);
        }
    }
}

UWP:

using Windows.Storage;
...

[assembly: Dependency(typeof(FileHelper))]
namespace Todo.UWP
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string filename)
        {
            return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
        }
    }
}

然后去检索和使用 最简单的方法是使用Xamarin的DependencyService。更多信息here

这里是the official documentation about local databases

希望对你有帮助!

【讨论】:

  • 另外,您不需要事先创建数据库。 SQLite 和使用 SQLite.Net-PCL 的 Xamarin 实现使用代码优先方法。您的数据模型 (C#) 将为您构建数据库表。看TaiT发的文章
猜你喜欢
  • 1970-01-01
  • 2019-08-25
  • 2018-07-25
  • 2020-07-19
  • 2016-06-22
  • 1970-01-01
  • 2013-03-30
  • 2019-01-11
  • 1970-01-01
相关资源
最近更新 更多