ExecuteScalar抛出NullReferenceException

时间:2009-02-18 02:34:41

标签: asp.net sql-server

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

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();

2 个答案:

答案 0 :(得分:12)

我已将大部分SQL逻辑封装在DAL中。其中一个DAL方法使用以下逻辑拉取标量Ints。它可能适合你:

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

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

答案 1 :(得分:6)

如果查询没有返回任何记录,则

ExecuteScalar返回null(例如,当您的SearchForPassenger存储过程没有返回任何行时)。

所以这一行:

item = (int) command.ExecuteScalar();

在这种情况下,是否尝试将null投射到int。这会引发NullReferenceException

根据刚刚弹出的Mark's answer,您需要检查null

object o = command.ExecuteScalar();
item = o == null ? 0 : (int)o;