SQL注入代码c# SQL server

本文关键字:SQL server 代码 注入 | 更新日期: 2023-09-27 17:54:41

这是我的c#代码

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    MultiView1.ActiveViewIndex = 0;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["preconn"].ToString());
SqlCommand com = new SqlCommand("select * from slab where salbn='" + DropDownList1.SelectedItem.Text + "'", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
    TextBox12.Text = reader["basic"].ToString();
    TextBox13.Text = reader["hra"].ToString();
    TextBox15.Text = reader["trvl"].ToString();
    TextBox16.Text = reader["mdeca"].ToString();
    TextBox18.Text = reader["atnd"].ToString();
    TextBox20.Text = reader["tote"].ToString();
    TextBox21.Text = reader["salbn"].ToString();
}
con.Close();
}
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 = @salb", con);
com.Parameters.Add("@salb", DropDownList1.SelectedItem.Text);
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");
}

这个代码是安全的SQL注入…??

如果没有,请纠正我的代码。我使用的是SQL server 2008.

SQL注入代码c# SQL server

DropDownList1_SelectedIndexChanged方法上使用Parameters,正如您在Button1_Click中所做的那样。每个查询都使用ADO。. NET使用参数会更安全。我会为连接关闭做try/catch/finally块,为ado.net对象做using()范围(记住using()范围需要在实现IDisposable接口的对象中)。它将在执行后从堆中删除对象,例如:

using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["preconn"].ToString()))
{
    try
    {
        SqlCommand com = new SqlCommand("select * from slab where salbn=@salbn", con);
        com.Parameters.Add("@salb", DropDownList1.SelectedItem.Text);
        con.Open();
        using(SqlDataReader reader = com.ExecuteReader())
        {
            if (reader.Read())
            {
                TextBox12.Text = reader["basic"].ToString();
                TextBox13.Text = reader["hra"].ToString();
                TextBox15.Text = reader["trvl"].ToString();
                TextBox16.Text = reader["mdeca"].ToString();
                TextBox18.Text = reader["atnd"].ToString();
                TextBox20.Text = reader["tote"].ToString();
                TextBox21.Text = reader["salbn"].ToString();
            }
        }
    }
    catch (Exception e)
    {
    }
    finally
    {
        con.Close();
    }
}