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.
Author: Wheat