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

标签 c# sqlite windows-phone-8

我一直在尝试创建一个 Windows Phone,我想使用 SQLite 来存储我的数据并学习如何在 Windows Phone 应用程序上使用它。为此,我使用“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);               
        }

我想我可能会收到此错误,因为我手动创建了一个空文件,但如果这是问题所在,如果手机中不存在数据库,我该如何创建数据库?

最佳答案

您不需要自己创建文件,因为 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,表只有在它们还不存在时才会被创建。

关于c# - SQLite.Net-PCL 连接找不到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23523763/

相关文章:

windows-phone-8 - Windows MDM 服务器 SyncML 协议(protocol)实现

c# - ASP :UpdatePanel - Add JavaScript on Button Click

c# - 无法嵌入。改用适用的接口(interface)

c# - 标签文本向上移动

c - sqlite c api插入绑定(bind)

c# - 在 Windows Phone 上保留 HTTPOnly cookie

c# - 在 C# (VTSO) 中将 Excel FitToPagesWide 设置为 "Automatic"

sqlite - 如何检查索引是否包含 SQLite 中的特定列

java - 将 mm-dd-yyyy 转换为 yyyy-mm-dd

c# - 加载图像时出现 WP8 内存不足错误