【发布时间】: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,null和DBNull.Value都会产生与我上面列出的相同的错误。我刚刚使用显式数据类型尝试了Add(),并得到了相同的结果。目标字段可以为空,但无论如何这都没有实际意义,因为没有执行 SQL,问题出在参数绑定上。 -
尽管文档说了什么,我还是很想避免 AddWithValue:请参阅can we stop using AddWithValue。我可以发誓我之前看到了一个问题,它暗示了为什么 null 可能会发生这种情况,但我找不到。
-
@Richardissimo,点了,但与我的问题无关;我使用
Add()方法得到了同样的错误。