我在 .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
?
最佳答案
我现在对 SQLite 有了更多的经验,并根据经验确定了答案。
我现在不确定最初发布此问题时导致我出现问题的确切情况。
与开头的问题相反,这确实有效:
cd.Parameters.AddWithValue("@param2", DBNull.Value);
直接 null
将抛出 value must be set
异常。如果参数值为 null
,我现在正在检测它并将其转换为包装类中的 DBNull.Value
。
在过去的一个月里,这个解决方案对我来说非常可靠。
关于c# - System.InvalidOperationException : Value must be set. 为 SQLite 设置空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751290/