1
    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();
           .............

给出的错误是“Invalid column name 'S29'”问题是,ID 只是 S29,没有单引号。但是,当 sql catch 带有 ''. 任何想法??

4

3 回答 3

3

永远不要永远不要使用字符串连接来将值替换到你的 sql 查询中。你要这个:

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(); 

使用您的旧代码,如果我设法创建了一个名为 的 ID;DROP Table Survey;--怎么办?

于 2011-12-19T02:10:22.913 回答
0

也许这个可以帮助你:

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();
       .............
于 2011-12-19T02:09:01.090 回答
-1

尝试:

string surveysr = "Select ShowResult from Survey where SurveyID='" + ID + "'" ;
于 2011-12-19T02:08:40.390 回答