asp.net – ExecuteScalar抛出NullReferenceException

此代码在调用ExecuteScalar时抛出NullReferenceException:

selectedPassengerID = 0;

//SqlCommand command = GenericDataAccess.CreateCommand();


// 2nd test
string connectionString = "";
SqlConnection conn;

connectionString = ConfigurationManager.
    ConnectionStrings["ConnST-MHM"].ConnectionString;
conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure ;
command.Connection = conn;
command.CommandText = "SearchForPassenger";

SqlParameter param;

param = command.CreateParameter();
param.ParameterName = "@name";
param.Value = pName; // Session[""];
param.DbType = DbType.String;
command.Parameters.Add(param);

param = command.CreateParameter();
param.ParameterName = "@flightDate";
param.Value = date; 
param.DbType = DbType.String;
command.Parameters.Add(param);

param = command.CreateParameter();
param.ParameterName = "@ticketNo";
param.Value = ticketNumber; 
param.DbType = DbType.Int32;
command.Parameters.Add(param);

int item;

command.Connection.Open();
item = (int)command.ExecuteScalar();
我已将大部分SQL逻辑封装在DAL中.其中一个DAL方法使用以下逻辑拉取标量Ints.它可能适合你:

  object temp = cmnd.ExecuteScalar();
  if ((temp == null) || (temp == DBNull.Value)) return -1;
  return (int)temp;

我知道你已经输入了很多代码,但我认为这确实是你问题的本质.祝你好运!

https://stackoverflow.com/questions/559632/executescalar-throws-nullreferenceexception

转载注明原文:asp.net – ExecuteScalar抛出NullReferenceException