如何通过隔离存储访问SQLite数据库?

时间:2014-09-20 11:04:04

标签: c# sqlite windows-phone-8 isolatedstorage

我尝试通过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时是否遗漏了任何内容?

1 个答案:

答案 0 :(得分:0)

最小的例子怎么样?它创建一个数据库,其表格与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>();
            }
        } 
    }
}