繁体   English   中英

如何使用 SQLite.net 创建数据库文件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM