如何在asp.net c#中的查询中插入变量?

时间:2016-03-04 10:49:03

标签: c# sql-server

protected void Button1_Click(object sender, EventArgs e)
{
    string email = Request.QueryString["Email"];
    cmd.Connection = cn;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = String.Format("INSERT INTO Job (Industry, JobPosition, ExactAddress, Region, Salary, JobDesc, EmployerID) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','Select employerid from employer where email = email')", Industry.SelectedValue.ToString(), TextBox3.Text, TextBox5.Text, Region.SelectedValue.ToString(), TextBox6.Text, TextBox7.Text, email.ToString()); 
    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();
    Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Job Posted!');</script>");
    Response.Redirect("EmployerProfile.aspx");
}

1 个答案:

答案 0 :(得分:1)

您的方法对SQL注入是开放的。你应该试试这个:

    protected void Button1_Click(object sender, EventArgs e)
    {
        string email = Request.QueryString["Email"];
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "INSERT INTO Job (Industry, JobPosition, ExactAddress, Region, Salary, JobDesc, EmployerID) VALUES (@industry, @jobPosition, @exactAddress, @region, @salary, @jobDesc, (Select employerid from employer where email = @email))";
        cmd.Parameters.Add("@industry", SqlDbType.VarChar, 255).Value = Industry.SelectedValue.ToString();
        cmd.Parameters.Add("@jobPosition", SqlDbType.VarChar, 255).Value = TextBox3.Text;
        cmd.Parameters.Add("@exactAddress", SqlDbType.VarChar, 255).Value = TextBox5.Text;
        cmd.Parameters.Add("@region", SqlDbType.VarChar, 255).Value = Region.SelectedValue.ToString();
        cmd.Parameters.Add("@salary", SqlDbType.VarChar, 255).Value = TextBox6.Text;
        cmd.Parameters.Add("@jobDesc", SqlDbType.VarChar, 255).Value = TextBox7.Text;
        cmd.Parameters.Add("@email", SqlDbType.VarChar, 255).Value = email.ToString();
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
        cmd.Parameters.Clear();
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Job Posted!');</script>");
        Response.Redirect("EmployerProfile.aspx");
    }

另外:您的方法无效,因为您的内部SELECT已按此过滤email = email