2014-03-28 127 views
0

這裏是我的代碼:錯誤的更新語句

protected void Button1_Click(object sender, EventArgs e) 
{ 

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["preconn"].ToString()); 

    con.Open(); 

    SqlCommand com = new SqlCommand("update slab set salbn = @salbn,basic = @basic,hra = @hra,trvl = @trvl,mdeca = @mdeca,atnd = @atnd,tote = @tote where salbn =" + DropDownList1.SelectedItem.Text, con); 

    com.Parameters.AddWithValue("@salbn", TextBox21.Text); 
    com.Parameters.AddWithValue("@basic", TextBox12.Text); 
    com.Parameters.AddWithValue("@hra", TextBox13.Text); 
    com.Parameters.AddWithValue("@trvl", TextBox15.Text); 
    com.Parameters.AddWithValue("@mdeca", TextBox16.Text); 
    com.Parameters.AddWithValue("@atnd", TextBox18.Text); 
    com.Parameters.AddWithValue("@tote", TextBox20.Text); 

    com.ExecuteNonQuery(); 

    con.Close(); 

    MsgBox("Updated Successfully"); 

} 

我得到了一個錯誤:「無效的列名稱Group_A'」 我的查詢是像設置 「更新平板salbn = @salbn, basic = @ basic,hra = @ hra,trvl = @ trvl,mdeca = @ mdeca,atnd = @ atnd,tote = @tote where salbn = Group_A「

這裏Group_A是DropDownList1.SelectedItem.Text。我正在使用asp.net/C#,sql server2008。

+5

爲什麼除了'DropDownList1.SelectedItem.Text'之外的所有東西都使用sql參數? –

回答

4

該值需要用單引號括起來。

SqlCommand com = new SqlCommand("update slab set salbn = @salbn,basic = @basic,hra = @hra,trvl = @trvl,mdeca = @mdeca,atnd = @atnd,tote = @tote where salbn ='" + DropDownList1.SelectedItem.Text + "'", con); 

話雖如此,你真的應該在WHERE子句中使用參數化的SQL,就像你在其他地方用來防止SQL注入攻擊一樣。

SqlCommand com = new SqlCommand("update slab set salbn = @salbn,basic = @basic,hra = @hra,trvl = @trvl,mdeca = @mdeca,atnd = @atnd,tote = @tote where salbn = @param", con); 
com.Parameters.AddWithValue("@param", DropDownList1.SelectedItem.Text);