我一直在尝试创建一个 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/