System.InvalidOperationException:必须设置值。为 SQLite 设置空参数

Eri*_*ric 7 c# sqlite

我在 .NETStandard 2.0 和 .NET Core 2.1.0 上使用 Microsoft.Data.Sqlite 2.1.0 与本地 SQLite 数据库交互。SQLitePCL 是在异常中提到的,也是一个依赖项。

我希望能够将参数的值设置为,NULL但是当我这样做时,我得到一个异常,即参数的“必须设置值”。

SqliteCommand cd = cn.CreateCommand();
cd.CommandText = sql;
cd.Parameters.AddWithValue("@param1", null); //This fails
cd.Parameters.AddWithValue("@param2", DBNull.Value); //This also fails
cd.Parameters.AddWithValue("@param3", ""); //This insert an empty string, not a NULL
cd.ExecuteNonQuery(); //The exception is thrown on this line
Run Code Online (Sandbox Code Playgroud)

完全例外:

{System.InvalidOperationException: Value must be set.
  at Microsoft.Data.Sqlite.SqliteParameter.Bind (SQLitePCL.sqlite3_stmt stmt) [0x0004c] in <56cfa09aae23467e945f1a64a1f893bb>:0 
  at (wrapper remoting-invoke-with-check) Microsoft.Data.Sqlite.SqliteParameter.Bind(SQLitePCL.sqlite3_stmt)
  at Microsoft.Data.Sqlite.SqliteParameterCollection.Bind (SQLitePCL.sqlite3_stmt stmt) [0x00017] in <56cfa09aae23467e945f1a64a1f893bb>:0 
  at (wrapper remoting-invoke-with-check) Microsoft.Data.Sqlite.SqliteParameterCollection.Bind(SQLitePCL.sqlite3_stmt)
  at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader (System.Data.CommandBehavior behavior) [0x0025d] in <56cfa09aae23467e945f1a64a1f893bb>:0 
  at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader () [0x00000] in <56cfa09aae23467e945f1a64a1f893bb>:0 
  at MyApp.DbHelper.BuildDataSet (Microsoft.Data.Sqlite.SqliteCommand cd) [0x00019] in C:\...\MyApp\DbHelper.cs:55 }
Run Code Online (Sandbox Code Playgroud)

根据官方文档,该值“可以为空”。

我尝试创建一个新的 SqliteParameter 并将值设置为 null,认为 AddWithValue() 可能存在问题,但这会产生相同的结果。

如何将 SqliteParameter 的值设置为NULL

Eri*_*ric 11

我现在对 SQLite 有了更多的经验,并通过经验确定了答案。

我现在不确定最初发布此问题时导致我出现问题的确切情况。

与开头的问题相反,这确实有效:

cd.Parameters.AddWithValue("@param2", DBNull.Value);
Run Code Online (Sandbox Code Playgroud)

直接null将抛出value must be set异常。如果参数值为null,我现在正在检测它并将其转换DBNull.Value为包装类。

在过去的一个月里,这个解决方案对我来说非常可靠。

  • 您可能还需要转换为对象:/sf/ask/759723401/#10853351 (2认同)