2016-11-14 95 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'這裏? –

相關問題