1

I want to read an sqlite database in my Windows Store application, if it exists...

Usually to read a table from database, i set the path where it's located, and then i call the SQLiteConnection function...

The questions is, why if the database not exists when i call a simple function like this

public static async Task<ObservableCollection<Objects>> GetAll()
    {
        List<Objects> list;
        using (var db = new SQLiteConnection(dbPath))
        {
            // Activate Tracing
            db.Trace = true;

            list = (from p in db.Table<Objects>()
                            select p).ToList();

        }

a database is created?

The empty database is created when new SQLiteConnection(dbPath) is invoked. is possible to open a connection without create it?

2 Answers 2

5

If you'll look at the code of the constructor you're using -

public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false)
            : this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)
{
}

You'll see that it passes in a flag that instructs SQLite to create the DB if it does not exist.

To avoid this, just use another constructor -

public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)

Like this -

using (var db = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite))

Keep it mind that this will thrown an SQLiteException if the DB does not exist.

Another possible solution would be to manually check for the presence of the file before opening.

Sign up to request clarification or add additional context in comments.

Comments

0
public async Task<bool> IsDbExists(string fileName)
    {
        try
        {
            var item = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
            var db = new SQLiteConnection("Your db path");
            var tb1 = db.GetTableInfo("TableName1");
            var tb2 = db.GetTableInfo("TableName2");
            var tb3 = db.GetTableInfo("TableName3");
            var tb4 = db.GetTableInfo("TableName4");
            if (item == null || tb1.Count == 0 || tb2.Count == 0 || tb3.Count == 0 || tb4.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.