2017-09-25 61 views
0

我已經創建了一個SQLite數據庫(使用cmd shell sqlite3.exe),現在正試圖在Xamarin.Forms內使用此頁面https://developer.xamarin.com/guides/android/application_fundamentals/data/part_3_using_sqlite_orm/作爲指導來實現它。不過,我很困惑,因爲我不知道數據庫的路徑是什麼。我將數據庫命名爲「app」和表「tbl1」,但這些都是我知道的關於它的所有信息。數據庫只存儲用戶名和密碼,並僅用於我的跨平臺應用程序的登錄頁面。在Xamarin.Forms中使用SQLite數據庫

+0

您正在查看的示例適用於Android。相當於Xamarin.Forms可以在這裏找到:https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/databases/ –

回答

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

希望它有幫助!

+0

此外,你不需要事先創建數據庫。 SQLite和使用SQLite.Net-PCL的Xamarin實現使用代碼優先方法。您的數據模型(C#)將爲您構建數據庫表。看看TaiT發佈的文章 – Joagwa