我在.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
?
答案 0 :(得分:3)
我现在对SQLite有更多的经验,并通过经验确定了答案。
我现在不确定当我最初发布此问题时导致我出现问题的确切情况。
与开头的问题相反,这确实有效:
cd.Parameters.AddWithValue("@param2", DBNull.Value);
直接null
会抛出value must be set
异常。如果参数值是null
,那么我现在正在检测它,并在包装器类中将其转换为DBNull.Value
。
在过去的一个月中,该解决方案对我来说非常可靠。