我遇到了抛出 NullReferenceException 的问题。这是代码:
using (SqlConnection connection = new SqlConnection(@"server=localhost\SQL2005;database=UintaTest;Integrated Security=SSPI;Connect Timeout=240"))
using (SqlCommand command = new SqlCommand(@"SELECT * FROM tblCaseActual WHERE CaseID = @Param", connection))
{
connection.Open();
connection.StatisticsEnabled = true;
SqlParameter commandParameter = new SqlParameter
{
ParameterName = "Param",
SqlDbType = SqlDbType.VarChar,
Size = 12,
Value = "1-19"
};
command.Parameters.Add(commandParameter);
command.Prepare();
//this does not throw an exception
command.ExecuteNonQuery();
//This throws an exception
command.ExecuteNonQuery();
}
调用第二个“ExecuteNonQuery”函数时会引发异常。第一个电话工作正常。
我查看了这个msdn 链接,但没有帮助。那里的代码片段与我正在尝试做的非常相似。我也搜索了其他有类似问题的人,但我没有找到任何东西。
并非所有 SQL 语句都会发生这种情况,但我已经在几个不同的数据库和几个不同的表上重现了它。
这里也是堆栈跟踪:
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at SqlCommandPrepareTest.Program.Main(String[] args) in C:\Users\jadams\Documents\Visual Studio 2010\Projects\SqlCommandPrepareTest\SqlCommandPrepareTest\Program.cs:line 33
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
任何帮助,将不胜感激。谢谢。