2016-11-14 131 views
0

这是我第一次尝试使用Visual Studio 2015制作跨平台应用程序。借助网上提供的教程,我可以在UWP(Xamarin Forms)中使用SQLite。但是,我不知道如何复制预填充的SQLite数据库并使用它?如何在UWP中使用预填充的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 
    } 
} 

回答

1

部署预填充的SQLite数据库“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; 
} 
+0

谢谢您的答复。但是我特别提到UWP(通用Windows编程),因为它显示错误 - ''Application'不包含'GetResourceStream'的定义。'对于iOS和Android,我已经使用另一个教程在网上工作。而且我没有使用WP8 –

+0

@ Dr.AtulTiwari在答案中添加了UWP信息。请检查 – Nikita

+0

谢谢,但我仍然有疑问。什么是'someObj'这里? –

相关问题