Question

    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??

Was it helpful?

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;--?

OTHER TIPS

Maybe this one can help you :

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

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

try:

string surveysr = "Select ShowResult from Survey where SurveyID='" + ID + "'" ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top