I am trying to make an alert system that checks a medications linked allergies with a patients linked allergies (see image below).
When I run the code it seems to just completely skip the SQLDataReader, I have performed checks on if(reader.HasRows) and it just shows there are no rows in the reader. All I want to do is show a message box with the selected allergy name at the end of the reader. I am using SQL Server 2014.Any help will be greatly appreciated.
private void button_addItem_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(comboBox_select_Item.Text.ToString()))
{
using (SqlConnection conn = new SqlConnection(connection))
{
try
{
SqlCommand sqlCmd2 = new SqlCommand("SELECT allergyName, allergyDescription FROM Allergies A INNER JOIN PatientAllergies PA ON A.allergyID = PA.allergyID WHERE A.allergyID = PA.allergyID AND PA.allergyID = (SELECT allergyID FROM Medication_Allergies MA WHERE MA.medID = " + comboBox_select_Item.SelectedValue.ToString() + ")", conn);
conn.Open();
SqlDataReader sqlReader = sqlCmd2.ExecuteReader();
Allergies allergies = new Allergies();
while (sqlReader.Read())
{
allergies.allergyName = Convert.ToString(sqlReader["allergyName"]);
allergies.allergyDescription = Convert.ToString(sqlReader["allergyDescription"]);
}
MessageBox.Show(allergies.allergyName);
sqlReader.Close();
FillSalesItemGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), ex.ToString());
}
}
}
}
First of all your SqlCommand is vulnerable to sql injections attack - you should always use SqlParameter as it helps you to prevent sql injections. So your SqlCommand should looks like :
SqlCommand sqlCmd2 = new SqlCommand("SELECT allergyName, allergyDescription FROM Allergies A INNER JOIN PatientAllergies PA ON A.allergyID = PA.allergyID WHERE A.allergyID = PA.allergyID AND PA.allergyID = (SELECT allergyID FROM Medication_Allergies MA WHERE MA.medID = @medID)", conn);
and you can pass parameter:
sqlCmd2.Parameters.AddWithValue("@medID",comboBox_select_Item.SelectedValue);
What is more, following statement in your query is redundant
WHERE A.allergyID = PA.allergyID
because you have INNER JOIN on this field
FROM Allergies A INNER JOIN PatientAllergies PA ON A.allergyID = PA.allergyID
so you can remove redundant statement from your query
SELECT allergyName, allergyDescription FROM Allergies A INNER JOIN PatientAllergies PA ON A.allergyID = PA.allergyID WHERE PA.allergyID = (SELECT allergyID FROM Medication_Allergies MA WHERE MA.medID = @medID)
I'm pretty sure that rest of your code is more or less fine. Please have a look if your query returns any rows. For example you can copy your query and replace @medID with value from your comboBox.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.