没有更新sql server数据库。没有错误只是没有结果

时间:2013-08-23 20:35:08

标签: c# sql-server

//the @Question column name needs to change according to the checkbox. For example Checkbox1 - Question1

SqlConnection con = new SqlConnection(...);
String sql = "UPDATE INQUIRY2 set @Question = @str WHERE email = @email AND base = @base;";

SqlCommand cmd = new SqlCommand(sql, con);
con.Open();

    //checkbox2 - question 2
    //if (CheckBox3.Checked == true)
    //{
      //  str = str + CheckBox3 + 'x';
    //}


    DataTable theDataTable = null;

       // Verify that dt is actually in session before trying to get it

        if(Session["dt"] != null)
        {
            theDataTable = Session["dt"] as DataTable;
        }

    //Verify that the data table is not null
    if(theDataTable != null)
    {
        email = theDataTable.Rows[0]["email"].ToString();
        base1 = theDataTable.Rows[0]["base"].ToString();

    }
    //checkbox1 - question 1
    if (CheckBox9.Checked == true)
    {
        str = str + CheckBox9.Text + 'x';
        strQuestOne = theDataTable.Columns["Question1"].ToString();

    }


    cmd.Parameters.AddWithValue("@email", email);
    cmd.Parameters.AddWithValue("@str", str);
    cmd.Parameters.AddWithValue("@Question", strQuestOne);
    cmd.Parameters.AddWithValue("@base", base1);


    cmd.ExecuteNonQuery();
    con.Close();

2 个答案:

答案 0 :(得分:3)

您正在使用列名称的参数。数据库对象(列名,表,存储过程或任何其他对象)不能作为参数传递。只有列或变量的实际值可以是参数。在这种情况下,您需要动态构建SQL语句:

String sql ="UPDATE INQUIRY2 set " + strQuestOne + "= @str WHERE email = ...

但是现在你应该小心,因为你的代码存在SQL注入攻击的风险。

答案 1 :(得分:0)

您的SQL在字符串中使用@param类型。

如果您希望执行某种存储过程来消除网站上的大多数SQL注入攻击,您可能需要考虑调用存储过程并将SqlCommand.Parameter添加到SqlCommand.Parameters集合。

否则,如果你只想执行sql,你应该这样做

string sql = String.Format(“UPDATE TABLE set COLUMN = {0} where OTHERCOLUMN = {1}”,varValue,varWhere);