SQLite not storing/retrieving database

荒凉一梦 提交于 2019-12-10 22:57:57

问题


I've got a Windows 10 UWP application written in C#. I'm using SQLite to store my data locally. The issue I'm experiencing is that the file is never saved and/or retrieved using this code. It should work, but I can't find out what's wrong.

dbExists always evaluates to false, so what am I missing here?

private SQLiteConnection localConn;
private string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "myDatabase.db");

public async void DBInit()
{
    bool dbExists = false;
    try
    {
        var store = await ApplicationData.Current.LocalFolder.GetFileAsync(dbPath);
        dbExists = true;
    }
    catch { dbExists = false; }
    if (!dbExists)
    {
        using (localConn = new SQLiteConnection(new SQLitePlatformWinRT(), dbPath))
        {
            // Create table
            localConn.CreateTable<MyTable>();
        }
    }
    else // CURRENTLY NOT FIRING!!
    {}
}

回答1:


Please consider using below code to create and access database file:

StorageFile notesFile = await storageFolder.CreateFileAsync(dbPath, CreationCollisionOption.OpenIfExists);

This will create new file if it does not exists and retrieve it when it is already created.

Please check my blog article to see more about UWP Data Storage: https://mobileprogrammerblog.wordpress.com/2016/05/23/universal-windows-10-apps-data-storage/




回答2:


I think you're missing this important piece of code:

SQLiteConnection.CreateFile("mydatabase.sqlite");

Do that first, then create a connection instance referencing the (now) created file.

Also, I'd suggest that you name the db with the .sqlite extension, so that the rest of the team and incoming devs, when then look at the db file artifact, can immediately tell that this is an sqlite database.

EDIT: The method is a static method. So you would use it like this...

using System.Data.SQLite;

namespace sqlite_sample
{
    class Program
    {
        static void Main(string[] args)
        {
            SQLiteConnection.CreateFile("sample.db");
        }
    }
}

The following will not work:

var conn = SQLiteConnection(...);
conn.CreateFile(dbPath);  //<-- static methods can't be invoked at the instance level...


来源:https://stackoverflow.com/questions/37731158/sqlite-not-storing-retrieving-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!