【问题标题】:System.InvalidOperationException: Value must be set. Setting Null Parameters for SQLiteSystem.InvalidOperationException:必须设置值。为 SQLite 设置 Null 参数
【发布时间】:2019-01-15 23:46:27
【问题描述】:

我在 .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

完全例外:

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

根据official documentation,值“可以为空”。

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

如何将 SqliteParameter 的值设置为 NULL

【问题讨论】:

  • 你试过null而不是DBNull.Value吗?不确定,但可能会起作用。
  • 您没有分享“这失败”时的 2 个错误。如果该列允许空值,则 DBNull 将起作用。此外,您应该使用Add 而不是AddWithValue,尤其是与 SqlIte 一起使用时,您可以控制它感知的数据类型。
  • @sawbeanraz,我试过null,请阅读我的问题。 @Plutonix,nullDBNull.Value 都会产生与我上面列出的相同的错误。我刚刚使用显式数据类型尝试了Add(),并得到了相同的结果。目标字段可以为空,但无论如何这都没有实际意义,因为没有执行 SQL,问题出在参数绑定上。
  • 尽管文档说了什么,我还是很想避免 AddWithValue:请参阅can we stop using AddWithValue。我可以发誓我之前看到了一个问题,它暗示了为什么 null 可能会发生这种情况,但我找不到。
  • @Richardissimo,点了,但与我的问题无关;我使用 Add() 方法得到了同样的错误。

标签: c# sqlite


【解决方案1】:

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

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

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

cd.Parameters.AddWithValue("@param2", DBNull.Value);

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-04-28
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多