【问题标题】:How can I create a database file with SQLite-net?如何使用 SQLite-net 创建数据库文件?
【发布时间】:2021-10-02 10:55:43
【问题描述】:

我在我的 UWP 应用程序中使用 SQLite-net nuget 包。我想创建一个本地数据库文件这样使用:

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 时遇到的权限问题。我需要设置哪些功能?

【问题讨论】:

  • 它不是组件的一部分吗?
  • 不,我没有看到SQLiteConnection.CreateFile 的方法。我正在使用 1.5.231 的版本 sqlite-net-pcl
  • 你用过this Nuget 包吗?
  • 是的,我确实使用了那个 nuget 包
  • @Darius,再次检查我的链接...

标签: c# sqlite


【解决方案1】:

检查您对该文件夹的权限,并尝试将其用于构造函数

_database = new SQLiteAsyncConnection(
     "myDbSQLite.db3", 
     SQLiteOpenFlags.Create | 
     SQLiteOpenFlags.FullMutex | 
     SQLiteOpenFlags.ReadWrite );

【讨论】:

    【解决方案2】:

    因为在 UWP 中创建文件必须使用 UWP API 完成,如果你要使用这个 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 提到的 this

    【讨论】:

    • 为什么不使用 dot net 标准的系统 IO。或者您的应用是否针对每个平台有不同的 IO 类?
    【解决方案3】:

    您应该使用具有写入权限的文件夹。所以请尝试以下代码:

    String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string dbFile = Path.Combine( path, "myDbSQLite.db3");
    var s = new SQLiteConnection( dbFile, SQLiteOpenFlags.Create);
    

    【讨论】:

    【解决方案4】:

    这对我有用:

     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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-27
      • 2020-12-21
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多