SQLite.Net-PCL连接找不到数据库

本文关键字:数据库 找不到 连接 Net-PCL SQLite | 更新日期: 2023-09-27 18:02:07

我一直在尝试创建一个windows手机,我想使用SQLite来存储我的数据,并学习如何在windows手机应用程序上使用它。为此,我使用"SQLite"。Net-PCL",但我不断得到一个文件没有发现例外。这是我写的代码:

        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);               
        }

我想也许我得到这个错误,因为我手动创建一个空文件,但如果这是问题,我怎么能创建一个数据库的情况下没有数据库存在于手机?

SQLite.Net-PCL连接找不到数据库

您不需要自己创建文件,因为SQLiteConnection构造函数会为您管理该文件。

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

所以你应该打开连接,创建表,应该是这样。

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>();
    }
}

不用担心Initialize,只有当表还没有出现的时候才会被创建。