ASP. NET 4 learning notes (1) SQL injection attacks and solutions.

Source: Internet
Author: User
Tags sql injection attack

I. Definition: the so-called SQL Injection Attack is the process that application developers did not expect to pass SQL code into the application, only applications that directly construct SQL statements using user-supplied values will be affected.

For example, the original SQL code is:

Select orders. customerid, orders. orderid, count (unitprice) as items, sum (unitprice * quantity) as total from orders inner join [Order Details] on orders. orderid = [Order Details]. orderid where orders. customerid = '"+ txtid. text + "'group by orders. orderid, orders. customerid

If. in the text box where text is located, input string: alfki 'or '1' = '1 will return all order records, even if those orders are not created by alfki, because for each line, 1 = 1 is always true.

Solution: Use parameterized commands:

For example, the preceding code is rewritten using parameterized commands:

 protected void btnQuery_Click(object sender, EventArgs e)
{
string conStr = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
con.Open();
string strSql = "select Orders.CustomerID,Orders.OrderID,Count(UnitPrice) as Items,SUM(UnitPrice*Quantity) as Total from Orders INNER JOIN [Order Details]on Orders.OrderID=[Order Details].OrderID where Orders.CustomerID=@CustomerID GROUP BY Orders.OrderID,Orders.CustomerID";
SqlCommand cmd = new SqlCommand(strSql, con);
cmd.Parameters.AddWithValue("@CustomerID", txtId.Text.Trim().ToString());
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
con.Close();
}

This prevents SQL injection attacks.

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.