I was hoping someone could help me out with this stupid problem I’m having with the following SQL statement:
public void ApplyInference(string AnswerSelected)
{
int InferenceID;
int QuestionID;
string AnswerInference;
int PainValue;
int AnxietyValue;
int DepressionValue;
int FearValue;
int TransportValue;
int EmotionalValue;
int FinancialValue;
int PhysicalValue;
int SpiritValue;
int SocialValue;
SqlConnection NewConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\QuestionsDatabase.mdf;Integrated Security=True;User Instance=True"); //"Initial Catalog=Northwind;Integrated Security=SSPI");
SqlDataReader ReadIn = null;
try
{
NewConnection.Open();
SqlCommand GetInference = new SqlCommand("SELECT * FROM InferenceDB WHERE QuestionID =" + this.QuestionID + "AND AnswerInference =" + AnswerSelected, NewConnection);
ReadIn = GetInference.ExecuteReader();
while (ReadIn.Read())
{
InferenceID = Convert.ToInt32(ReadIn[0]);
QuestionID = Convert.ToInt32(ReadIn[1]);
AnswerInference = Convert.ToString(ReadIn[2]);
PainValue = Convert.ToInt32(ReadIn[3]);
AnxietyValue = Convert.ToInt32(ReadIn[4]);
DepressionValue = Convert.ToInt32(ReadIn[5]);
FearValue = Convert.ToInt32(ReadIn[6]);
TransportValue = Convert.ToInt32(ReadIn[7]);
EmotionalValue = Convert.ToInt32(ReadIn[8]);
FinancialValue = Convert.ToInt32(ReadIn[9]);
PhysicalValue = Convert.ToInt32(ReadIn[10]);
SpiritValue = Convert.ToInt32(ReadIn[11]);
SocialValue = Convert.ToInt32(ReadIn[12]);
MessageBox.Show("InferenceID: " + InferenceID + "\nAnswer Value: " + AnswerInference + "\nPain value: " + PainValue + "\nSocial value: " + SocialValue);
//LoadQuestionForm(this.FormStyle);
}
}
finally
{
if (ReadIn != null)
{
ReadIn.Close();
}
if (NewConnection != null)
{
NewConnection.Close();
}
}
}`
Now the code works tor every other column in the table except for the one I need which is the AnswerInference one. I am feeding the AnswerInference value in from another method which looks like this:
private void Answer1Button_Click(object sender, EventArgs e)
{
parent.ApplyInference("Ans1");
CloseForm();
}
Unfortunately I can’t get the code to work using string data found in the table I’m using. I know this should be an easy fix, but I can for the life of me work out what’s going on. Can someone suggest what I’m doing wrong?
You need a space between the question-id and the and, but more importantly: you should use parameters. Look into “SQL injection”, query-plan re-use, etc. The most appropriate way to do this is with a command like:
Also – that complex-looking
try/finallycan be simplified withusinghere.