asp.net – ExecuteScalar抛出NullReferenceException

前端之家收集整理的这篇文章主要介绍了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://www.f2er.com/aspnet/251590.html

猜你在找的asp.Net相关文章