Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite.Net-PCL Connection not finding the DB

I've been trying to create a windows phone and I'd like to use SQLite to both store my data and learn how to use it on windows phone apps. For this purpose I'm using "SQLite.Net-PCL", but I keep getting a file not found exception. This the code I've written:

        String ConnectionString = Path.Combine(ApplicationData.Current.LocalFolder.Path, Connection);
        if (File.Exists(ConnectionString))
        {
            SQLite.Net.Platform.WindowsPhone8.SQLitePlatformWP8 e = new SQLite.Net.Platform.WindowsPhone8.SQLitePlatformWP8();
            Con = new SQLiteConnection(e,ConnectionString);
        }

        else {
            SQLite.Net.Platform.WindowsPhone8.SQLitePlatformWP8 e = new SQLite.Net.Platform.WindowsPhone8.SQLitePlatformWP8();
            File.Create(ConnectionString);
            Con = new SQLiteConnection(e, ConnectionString);               
        }

I thought maybe I get this error because I manually create an empty file but if that is the problem, how can I create a DB in case no database exists in the phone ?

like image 332
JAX Avatar asked Nov 10 '22 08:11

JAX


1 Answers

You don't need to create the file yourself, as the SQLiteConnection constructor manages that for you.

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

So you should just open the connection, create the tables and that should be that.

class ExampleDataContext
{
    public const string DATABASE_NAME = "data.sqlite";
    private SQLiteConnection connection;

    public TableQuery<Foo> FooTable { get; private set; }
    public TableQuery<Bar> BarTable { get; private set; }

    public ExampleDataContext()
    {
        connection = new SQLiteConnection(new SQLitePlatformWinRT(), Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, DATABASE_NAME));

        Initialize();

        FooTable      = connection.Table<Foo>();
        BarTable       = connection.Table<Bar>();
    }

    private void Initialize()
    {
        connection.CreateTable<Foo>();
        connection.CreateTable<Bar>();
    }
}

Don't worry about that Initialize, the tables only get created when they're not there yet.

like image 164
Benjamin Diele Avatar answered Nov 14 '22 23:11

Benjamin Diele