一, 定義:所謂SQL注入攻擊是應用程式開發人員未預期地把SQL代碼傳入到應用程式的過程,只有那些直接使用使用者提供的值構造SQL語句的應用程式才會受影響.
例如原SQL代碼為:
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
如果在txtId.Text所在的文字框中輸入字串:ALFKI' or '1'='1將會返回所有的訂單記錄,即便那些訂單不是由ALFKI建立的,因為對每一行而言,1=1總是為true.
解決方案:採用參數化命令:
如使用參數化命令重寫前面的代碼為:
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();
}
這樣就可以避免SQL注入攻擊.