![](/img/trans.png)
[英]Create SQLite database file with SQLite-net on Windows Phone 8
[英]How can I create a database file with SQLite-net?
我在我的 UWP 應用程序中使用 SQLite.net nuget package。 我想創建一個本地數據庫文件來使用:
var s = new SQLiteConnection("myDbSQLite.db3", SQLiteOpenFlags.Create);
但它拋出錯誤:
無法打開數據庫文件:C:\Path\MyProject\bin\x86\Debug\AppX\myDbSQLite.db3(誤用)
我在其他帖子中看到他們建議使用SQLiteConnection.CreateFile("MyDatabase.sqlite");
但我沒有看到那個方法?
編輯
代碼
FileStream fs = File.Create(path);
拋出異常:
UnauthorizedAccessException 對路徑的訪問被拒絕
所以我認為這是我在使用 UWP 時遇到的權限問題。我需要設置哪些功能?
檢查您對文件夾的權限,然后嘗試將其用於構造函數
_database = new SQLiteAsyncConnection(
"myDbSQLite.db3",
SQLiteOpenFlags.Create |
SQLiteOpenFlags.FullMutex |
SQLiteOpenFlags.ReadWrite );
您應該使用具有寫訪問權的文件夾。 因此,請嘗試以下代碼:
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dbFile = Path.Combine( path, "myDbSQLite.db3");
var s = new SQLiteConnection( dbFile, SQLiteOpenFlags.Create);
由於必須使用UWP API在UWP中創建文件,因此,如果您要使用此nuget庫,則必須先自己創建它以適應以下情況:
// Create the empty file; replace if exists.
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
storageFolder.CreateFileAsync("myDbSQLite.db3", Windows.Storage.CreationCollisionOption.ReplaceExisting);
我UWP應用程序實際上是使用共享代碼Xamarin.Forms應用程序的一部分,因此,如果您的應用程序僅僅是UWP有可能是一個更好的庫,如這一個Codexer簡稱。
這對我有用:
var databasePath = Path.Combine(GetLocalFileDirectory(), "MyData.db");
try
{
// Create the empty file; replace if exists.
db = new SQLiteAsyncConnection(databasePath,
SQLiteOpenFlags.Create |
SQLiteOpenFlags.FullMutex |
SQLiteOpenFlags.ReadWrite);
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
public string GetLocalFileDirectory()
{
var docFolder = FileSystem.AppDataDirectory
var libFolder = Path.Combine(docFolder, "Databases");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
return libFolder;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.