[英]How can I create a database file with SQLite-net?
I am using SQLite.net nuget package in my UWP application.我在我的 UWP 应用程序中使用 SQLite.net nuget package。 I want to create a local database file to use as such:我想创建一个本地数据库文件来使用:
var s = new SQLiteConnection("myDbSQLite.db3", SQLiteOpenFlags.Create);
But it throws the error:但它抛出错误:
Could not open database file: C:\Path\MyProject\bin\x86\Debug\AppX\myDbSQLite.db3 (Misuse)无法打开数据库文件:C:\Path\MyProject\bin\x86\Debug\AppX\myDbSQLite.db3(误用)
I see in other posts they suggest to use SQLiteConnection.CreateFile("MyDatabase.sqlite");
我在其他帖子中看到他们建议使用SQLiteConnection.CreateFile("MyDatabase.sqlite");
but I don't see that method?但我没有看到那个方法?
EDIT编辑
The code代码
FileStream fs = File.Create(path);
Throws the exception:抛出异常:
UnauthorizedAccessException access to the path is denied UnauthorizedAccessException 对路径的访问被拒绝
So I think this is a permission issue I am having with UWP. Is there something in the capabilities that I need to set?所以我认为这是我在使用 UWP 时遇到的权限问题。我需要设置哪些功能?
Check your permissions on the folder, and also try using this for the constructor 检查您对文件夹的权限,然后尝试将其用于构造函数
_database = new SQLiteAsyncConnection(
"myDbSQLite.db3",
SQLiteOpenFlags.Create |
SQLiteOpenFlags.FullMutex |
SQLiteOpenFlags.ReadWrite );
You should use a folder wher you have write-access to. 您应该使用具有写访问权的文件夹。 So please try the following code: 因此,请尝试以下代码:
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dbFile = Path.Combine( path, "myDbSQLite.db3");
var s = new SQLiteConnection( dbFile, SQLiteOpenFlags.Create);
Because creating a file in UWP must be done with the UWP API, if you're going to use this nuget library, you have to accommodate by creating it yourself first: 由于必须使用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);
My UWP app is actually part of a Xamarin.Forms app that is using shared code, so if your app is solely UWP there's probably a better library, such as this one that Codexer referred. 我UWP应用程序实际上是使用共享代码Xamarin.Forms应用程序的一部分,因此,如果您的应用程序仅仅是UWP有可能是一个更好的库,如这一个Codexer简称。
This worked for me:这对我有用:
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.