Avoid SQL injection : SqlCommand « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SqlInjectionCorrected" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:TextBox id="txtID" runat="server">ALFKI' OR '1'='1</asp:TextBox>
      <asp:Label id="Label1" runat="server">Enter Customer ID:</asp:Label>
      <asp:Button id="cmdGetRecords" runat="server" Text="Get Records" OnClick="cmdGetRecords_Click"></asp:Button>
      <asp:GridView id="GridView1" runat="server" Width="392px" Height="123px"></asp:GridView>
    </div>
    </form>
</body>
</html>


File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class SqlInjectionCorrected : System.Web.UI.Page
{
  protected void cmdGetRecords_Click(object sender, System.EventArgs e)
  {
    string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" +
      "Integrated Security=SSPI";
    SqlConnection con = new SqlConnection(connectionString);
    string 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 = @CustID " +
      "GROUP BY Orders.OrderID, Orders.CustomerID";
    SqlCommand cmd = new SqlCommand(sql, con);
    cmd.Parameters.Add("@CustID", txtID.Text);

    con.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    GridView1.DataSource = reader;
    GridView1.DataBind();
    reader.Close();
    con.Close();
  }
}








18.3.SqlCommand
18.3.1.Create SqlCommand from sql statement and connection
18.3.2.Executing a Command
18.3.3.Executing a Command with Parameters
18.3.4.Returning a Single Value
18.3.5.Read scalar data by using SqlCommand
18.3.6.Execute insert command by using SqlCommand
18.3.7.Execuate select command by using the SqlCommand
18.3.8.Execute update command
18.3.9.Attach SqlCommand to DataGrid
18.3.10.Pass a CommandBehavior.CloseConnection parameter to the ExecuteReader() method.
18.3.11.Executing Asynchronous Database Commands
18.3.12.Avoid SQL injection
18.3.13.Avoid SQL Injection attack
18.3.14.Browser Snoop