Search code examples
asp.netsqlselectclause

SQL Statement "invalid column name": how to build query?


    string ID = "";
        if (Session["sID"] != null)
        {
            ID = Session["sID"].ToString();
            con.Open();

            string surveysr = "Select ShowResult from Survey where SurveyID=" + ID ;
            SqlCommand cmd2 = new SqlCommand(surveysr, con);
            SqlDataReader dr = cmd2.ExecuteReader();
           .............

the error given was " Invalid column name 'S29' " the problem was, the ID is just S29, without the single quote. however, when the sql catch is with the ''. any idea??


Solution

  • Never NEVER NEVER use string concatenation to substitute values into your sql queries like that. You want this:

    string ID = "";
    if (Session["sID"] != null)
    {
        ID = Session["sID"].ToString();
        con.Open();
    
        string surveysr = "Select ShowResult from Survey where SurveyID= @ID";
        SqlCommand cmd2 = new SqlCommand(surveysr, con);
        cmd2.Parameters.Add("@ID", SqlDbType.VarChar, 3).Value = ID;
        SqlDataReader dr = cmd2.ExecuteReader(); 
    

    With your old code, what if I had managed to create an ID named ;DROP Table Survey;--?