我有用C#编写的Windows 10 UWP应用程序。 我正在使用SQLite在本地存储我的数据。 我遇到的问题是,该文件是从来没有保存和/或检索使用此代码。 它应该工作,但我不能找出什么是错的。
dbExists总是评估为false,所以我在这里错过了什么?
private SQLiteConnection localConn; private string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "myDatabase.db"); public async void DBInit() { bool dbExists = false; try { var store = await ApplicationData.Current.LocalFolder.GetFileAsync(dbPath); dbExists = true; } catch { dbExists = false; } if (!dbExists) { using (localConn = new SQLiteConnection(new SQLitePlatformWinRT(), dbPath)) { // Create table localConn.CreateTable<MyTable>(); } } else // CURRENTLY NOT FIRING!! {} }
请考虑使用下面的代码来创建和访问数据库文件:
StorageFile notesFile = await storageFolder.CreateFileAsync(dbPath, CreationCollisionOption.OpenIfExists);
这将创建新文件,如果它不存在,并检索它已经创建。
请检查我的博客文章,以查看有关UWP数据存储的更多信息: https : //mobileprogrammerblog.wordpress.com/2016/05/23/universal-windows-10-apps-data-storage/
我认为你错过了这段重要的代码:
SQLiteConnection.CreateFile("mydatabase.sqlite");
这样做,然后创建一个引用(现在)创建的文件的连接实例。
另外,我建议你用.sqlite扩展名来命名数据库,这样当团队和传入开发者的其余部分再次查看数据库文件工件时,可以立即知道这是一个sqlite数据库。
编辑:该方法是一种静态方法。 所以你会这样使用它…
使用System.Data.SQLite; 命名空间sqlite_sample { 上课程序 { static void Main(string [] args) { SQLiteConnection.CreateFile( “sample.db”); } } }
以下将不起作用:
var conn = SQLiteConnection(...); conn.CreateFile(dbPath); //<-- static methods can't be invoked at the instance level...