Can someone help me understand what's happening? I'm trying to get the
- SAQA ID
- NQF Level
- Credits
of a course but there's something I don't understand.
If I create a variable with my query such as
public Int32 T_Course_Id = 0, T_Company_Id = 0, T_Nqf = 0, T_Credit = 0;
string queryTaskId = "SELECT [course_saqa_id] FROM"+
"[sta].[dbo].[Courses]"+
"WHERE course_name = '" + _Coursename + "'";
string queryNqf = "SELECT [course_nqf]"+
"FROM [sta].[dbo].[Courses]"+
"WHERE course_saqa_id = '" + T_Course_Id + "'";
using (SqlConnection Conn = new SqlConnection(ConnString))
{
Conn.Open();
using (SqlCommand command = new SqlCommand(queryTaskId, Conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
// Call Read before accessing data.
T_Course_Id = reader.GetInt32(0);
}
// Call Close when done reading.
reader.Close();
}
}
using (SqlCommand command = new SqlCommand(queryCredit, Conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
// Call Read before accessing data.
T_Credit = reader.GetInt32(0);
}
// Call Close when done reading.
reader.Close();
}
}
Conn.Close();
}
If I do it this way I get a 0 value for the T_Credit variable, but if I do it like this (this is only the last part)
using (SqlCommand command = new SqlCommand("SELECT [course_nqf] FROM [sta].[dbo].[Courses] WHERE course_saqa_id = '" + T_Course_Id + "'", Conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
// Call Read before accessing data.
T_Credit = reader.GetInt32(0);
}
// Call Close when done reading.
reader.Close();
}
}
then I get the correct value, as you can see I'm passing the SQL command directly instead of a variable
using (SqlCommand command = new SqlCommand("SELECT [course_nqf] FROM [sta].[dbo].[Courses] WHERE course_saqa_id = '" + T_Course_Id + "'", Conn))
Why won't a variable work here ?
using() { ... }style?queryNqfinstead ofqueryCredit."SELECT [course_saqa_id] FROM " + "[sta].[dbo].[Courses]" + " WHERE course_name = @CourseName";- note the SPACE after theFROMand before theWHEREkeywords ....