如何通过独立存储访问SQLite数据库

本文关键字:SQLite 数据库 访问 存储 何通过 独立 | 更新日期: 2023-09-27 18:22:49

我试图通过IsolatedStorage访问我的新SQLite数据库,但当我这样做时:

new SQLiteConnection(_dbpath);

找不到数据库
这是我创建文件的代码:

IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoStore.FileExists("TestDB.sqlite"))
{
    isoStore.CreateFile("TestDB.sqlite");
}
_dbpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "SportInDB.sqlite");

在创建新的SQLiteConnection时,我错过了什么吗?

如何通过独立存储访问SQLite数据库

一个最小的例子怎么样?它创建了一个数据库,其中包含一个与class Question匹配的表。


// namespaces
using SQLite;
using System.IO;
using System.IO.IsolatedStorage;
using System.Threading.Tasks;
// define a class like table to create
public class Question
{
    [SQLite.PrimaryKey, SQLite.AutoIncrement]
    public int Id { get; set; }
    public int Status { get; set; }
} 
public partial class MainPage : PhoneApplicationPage
{
    string dbPath = "";
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        // combine the local folder with the file name of the database
        dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");                        
        CreateDBTable();            
    }
    // from the MSDN article for getting SQLite to work
    private async Task<bool> FileExists(string fileName)
    {
        var result = false;
        try
        {
            var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
            result = true;
        }
        catch
        {
        }
        return result;
    }
    // if the file doesn't exist, create it with the db.CreateTable
    public void CreateDBTable()
    {
        if (!FileExists("db.sqlite").Result)
        {
            using (var db = new SQLiteConnection(dbPath))
            {
                db.CreateTable<Question>();
            }
        } 
    }
}