【问题标题】:How to use pre-populated sqlite database in UWP?如何在 UWP 中使用预填充的 sqlite 数据库?
【发布时间】:2017-03-28 05:35:49
【问题描述】:

这是我第一次尝试使用 Visual Studio 2015 制作跨平台应用程序。在网上可用教程的帮助下,我能够在 UWP (Xamarin Forms) 中使用 SQLite。但是,我不知道如何复制预填充的 sqlite 数据库并使用它?

我的代码示例是 -

using Medical_Study.UWP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Xamarin.Forms;

[assembly: Dependency(typeof(SqliteService))]

namespace Medical_Study.UWP
{

    public class SqliteService : ISQLite
    {
        public SqliteService()
        {
        }
        #region ISQLite implementation
        public SQLite.SQLiteConnection GetConnection()
        {
            var sqliteFilename = "QBank.db";
            string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
            var conn = new SQLite.SQLiteConnection(path);

            // Return the database connection 
            return conn;
        }
        #endregion
    }
}

【问题讨论】:

    标签: sqlite xamarin visual-studio-2015 uwp xamarin.uwp


    【解决方案1】:

    要部署预填充的 SQLite DB“QBank.db”,您可以将其编译为应用程序的嵌入式资源,并在首次运行时将其复制到 LocalFolder 以供进一步使用。

    为此,将“QBank.db”包含到您的项目中并选择Build Action -> Embedded Resource

    GetConnection()方法可以这样实现:

    public SQLite.SQLiteConnection GetConnection()
    {
      var sqliteFilename = "QBank.db";
    
      var assembly = GetType().GetTypeInfo().Assembly;
      var qbankDbResource 
        = assembly.GetManifestResourceNames().FirstOrDefault(name => name.EndsWith(sqliteFilename));
      if (qbankDbResource == null)
      {
        Debug.Assert(false, string.Format("{0} database is not included as embedded resource", sqliteFilename));
        return null;
      }
    
      string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
      using (var qbankDbStream = assembly.GetManifestResourceStream(qbankDbResource))
      using (var fStream = new FileStream(path, FileMode.Create, FileAccess.Write))
      {
        qbankDbStream.CopyTo(fStream);
      }
    
      var conn = new SQLite.SQLiteConnection(path);
      // Return the database connection 
      return conn;
    }
    

    【讨论】:

    • 感谢您的回复。但我专门询问 UWP(通用 Windows 编程),因为它显示错误 - 'Application' does not contain a definition for 'GetResourceStream'. 对于 iOS 和 android,我已经从网上的另一个教程中使它工作。而且我没有使用 WP8
    • @Dr.AtulTiwari 在答案中添加了 UWP 信息。请检查
    • 谢谢,但我仍然有疑问。 someObj 这里是什么?
    • @Dr.AtulTiwari 它实际上是任何对象,其类型在与您的资源相同的程序集中声明。例如。在您的 GetConnection() 函数中,您可以使用 this.GetType().GetTypeInfo().Assembly
    • 感谢您提供更新的答案。它当然帮助了我。尽管在阅读您的答案之前,我也尝试过使用StorageFile,但它对我没有用,我可能会遗漏一些东西。但是,你的方法奏效了。谢谢
    猜你喜欢
    • 2016-04-12
    • 2012-10-19
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 2011-04-15
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多