将现有数据库加载到Universal app

时间:2014-07-02 10:22:26

标签: c# sqlite windows-runtime windows-8.1 win-universal-app

我正在尝试在Universal 8.1应用中加载现有的数据库文件。

我安装了所有必需的软件包,而我正在使用SQLitePCL包装器。

当我尝试使用此命令打开db文件时:

conn = new SQLiteConnection("test.db");

它正在创建一个新的空数据库。 (我的意思是,每个SELECT命令失败,没有这样的表错误。所以它不是我的数据库,它是一个新的。)

此外,

conn = new SQLiteConnection("ms-appx:///test.db");

抛出此异常:

  

无法打开数据库文件:ms-appx:///test.db详细信息:无法打开数据库文件

我的test.db位于共享项目的根目录中,Build Action设置为ContentCopy to Output Directory设置为If Newer

我不确定我做错了什么。你能救我吗?

  • 如果这是一个愚蠢的问题,请接受我的道歉,我是WinRT编程的新手。

1 个答案:

答案 0 :(得分:3)

sqlite-net包装器的解决方案,这也适用于SQLitePCLhttp://wp.qmatteoq.com/import-an-already-existing-sqlite-database-in-a-windows-8-application/

摘要是,那些包装器查找LocalStorage文件夹中的数据库。因此,在访问数据库之前,您需要将文件复制到LocalStorage

private async Task CopyDatabase()
{
    bool isDatabaseExisting = false;
 
    try
    {
        StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("people.db");
        isDatabaseExisting = true;
    }
    catch
    {
        isDatabaseExisting = false;
    }
 
    if (!isDatabaseExisting)
    {
        StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("people.db");
        await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
    }
}

之后,可以使用以下代码行访问数据库:

conn = new SQLiteConnection("test.db");

然而,问题是我将在手机中存储两个数据库文件实例。我不知道如何解决这个问题。有人可以帮忙吗?