Я пытаюсь вырезать ошибку в своем веб-приложении. В основном я пытаюсь реализовать систему бронирования ресторанов. Пользователь выбирает, сколько людей на вечеринке, сидя (обед или ужин) и дату. Затем система запрашивает мою базу данных, чтобы сообщить пользователю, есть ли доступность. Он работает, если в ресторане уже заказано несколько человек, но если запрос возвращает значение NULL (т. Е. Ресторан пуст), система выйдет из строя. Мне никогда не приходилось иметь дело с NULL перед тем, как это сделать, и я не понимаю, как справиться с этой ошибкой в коде, чтобы пользователь мог сделать заказ. Я прокомментировал свой код как можно лучше. Любая помощь очень ценится! :)Ошибка базы данных при возврате нулевого значения
protected void AvailabilityButton_Click(object sender, EventArgs e)
{
//Create SQL Database connection
// New sql connection and command
SqlConnection myconn = new SqlConnection();
myconn.ConnectionString = "Data Source=STUDENT2;Initial Catalog=HarryBistro;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = myconn;
myconn.Open();
//Check that selected date is today or later
if (Calendar1.SelectedDate <= DateTime.Today)
{
SuccessFailureLabel.Text = "Please select a date in the future";
SuccessFailureLabel.Visible = true;
}
else
{
//Create variables from user input
string SelectedBranch = BranchDropDownList.SelectedValue.ToString();
string SelectedSitting = SittingDropDownList.SelectedValue.ToString();
int SelectedDiners = Convert.ToInt32(DinersDropDownList.SelectedValue);
string SelectedDate = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
//Query to find out how many people have already booked into selected restaurant on selected date on selected sitting
cmd.CommandText = "select SUM(Number_Of_Seats) from RESERVATIONS where Sitting = '" + SelectedSitting + "' and Branch_ID = '" + SelectedBranch + "' and Date_Of_Booking = '" + SelectedDate + "' ";
//Assign the value of the people in the restaurant to a variable
int peopleinrestaurant = (int)cmd.ExecuteScalar();
//Query to find out how many people the selected restaurant seats
cmd.CommandText = "select SUM(Capacity) from BRANCH where Branch_ID = '" + SelectedBranch + "'";
//Assign the value of the people in the restaurant to a variable
int branchCapacity = (int)cmd.ExecuteScalar();
//add the amount of people in the party to the restaurant occupancy and assign to a variable
int totalOccupancy = peopleinrestaurant + SelectedDiners;
if (totalOccupancy <= branchCapacity)
{
//Show success message
SuccessFailureLabel.Visible = true;
SuccessFailureLabel.Text = "Booking available. Please proceed.";
//enable customer details text boxes so the customer can proceed
ConfirmBookingButton.Enabled = true;
}
else
{
//Show failure message if booking over capacity. Show user how many seats are available
SuccessFailureLabel.Visible = true;
SuccessFailureLabel.Text = "Cannot proceed. There are only " + (branchCapacity - peopleinrestaurant) + " seats available.";
}
}
}
Где yuo получить сообщение об ошибке? На первый взгляд кажется, что ваши люди в ресторане должны иметь значение 0, если нет заказов, а не null. При этом вы можете проверить, является ли объект NULL простым с if (object == null). – oerkelens
'ExecuteScalar' может возвращать значение null, которое нельзя передать в' int'. Перед литьем вы должны проверить его возвращаемое значение. –
Я стою исправлены. SUM() _does_ возвращает null, если записи не найдены. – oerkelens