Safety from SQL injection

前端 未结 3 851
栀梦
栀梦 2021-01-17 04:24
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[\"techconn\"].ToString());

            SqlCommand com = new SqlCommand(\"select * from          


        
3条回答
  •  我在风中等你
    2021-01-17 05:00

    Yes your code is quite prone to issues, not only sql injection attacks. Try the following:

        public DataTable GetData(string textbox1, string textbox2, string dropdown)
        {
            DataTable result = null;
            string connString = null;
    
            if (ConfigurationManager.ConnectionStrings["techconn"] != null)
                connString = ConfigurationManager.ConnectionStrings["techconn"].ConnectionString;
    
            if (!string.IsNullOrEmpty(connString))
            using (SqlConnection con = new SqlConnection(connString))
            {
                con.Open();
    
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "select * from hs where (ac between @a and @b) and em = @c";
    
                    cmd.Parameters.AddWithValue("@a", textbox1);
                    cmd.Parameters.AddWithValue("@b", textbox2);
                    cmd.Parameters.AddWithValue("@c", dropdown);
    
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        result = new DataTable();
                        da.Fill(result);
    
                    }
                }
            }
    
            return result;
    
        }
    

    Paste it in your code and use by

    DataTable dt = GetData(TextBox1.Text, TextBox2.Text, DropDownList1.SelectedItem.Text.ToString());
    
                if (dt != null && dt.Rows.Count > 0)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
                else
                {
                    GridView1.Visible = false;
                }
    

    Test it properly too.

提交回复
热议问题