此代码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();
Mark Brittin.. 12
我已将大部分SQL逻辑封装在DAL中.其中一个DAL方法使用以下逻辑拉取标量Ints.它可能适合你:
object temp = cmnd.ExecuteScalar(); if ((temp == null) || (temp == DBNull.Value)) return -1; return (int)temp;
我知道你已经输入了很多代码,但我认为这确实是你问题的本质.祝好运!
我已将大部分SQL逻辑封装在DAL中.其中一个DAL方法使用以下逻辑拉取标量Ints.它可能适合你:
object temp = cmnd.ExecuteScalar(); if ((temp == null) || (temp == DBNull.Value)) return -1; return (int)temp;
我知道你已经输入了很多代码,但我认为这确实是你问题的本质.祝好运!
ExecuteScalar
如果查询未返回任何记录,则返回null(例如,当您的SearchForPassenger
存储过程未返回任何行时).
所以这一行:
item = (int) command.ExecuteScalar();
试图投null
给int
在这种情况下.这会提高一个NullReferenceException
.
根据马克的答案刚刚弹出,您需要检查null
:
object o = command.ExecuteScalar(); item = o == null ? 0 : (int)o;