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

Était-ce utile?

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

Autres conseils

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 + "'" ;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top