In this article I will explain with an example, how to use parameterized queries to prevent SQL injection attacks in SQL Server.
What is Parameterized Query?
Parameterized queries are those in which values are passed using SQL parameters. Such queries are safe compared to queries built using string concatenation.
When queries are built using string concatenation, hackers can easily modify it by injecting SQL script.
Thus, the benefits of parameterized queries is that they protect the database from SQL injection.
I have made use of the following table Customers with the schema as follows.
Using Parameterized queries to prevent SQL Injection Attacks in SQL Server
Note: You can download the database table SQL by clicking the download link below.
         Download SQL file
HTML Markup
The HTML Markup consists of:
TextBox – For inputting Name and Country.
Button – For submitting the Form.
        <td><asp:TextBoxID="txtName"runat="server" /></td>
        <td><asp:TextBoxID="txtCountry"runat="server" /></td>
        <td><asp:ButtonID="btnSubmit"Text="Submit"runat="server"OnClick="Submit" /></td>
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
Imports System.Configuration
Imports System.Data.SqlClient
Using Parameterized queries to prevent SQL Injection Attacks
When the Submit Button is clicked, the name and country value are fetched from their respective TextBoxes and are passed as parameters to the SqlCommand object.
Finally, values are inserted into Database using ExecuteNonQuery function.
Note: For more details on ExecuteNonQuery function, please refer Using ADO.Net ExecuteNonQuery method in ASP.Net with examples in C# and VB.Net.
protected void Submit(object sender, EventArgs e)
    string query = "INSERT INTO Customers(Name, Country) VALUES(@Name, @Country)";
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
        using (SqlCommand cmd = new SqlCommand(query))
            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Connection = con;
Protected Sub Submit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim query As String = "INSERT INTO Customers(Name, Country) VALUES(@Name, @Country)"
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(conString)
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.Parameters.AddWithValue("@Name", txtName.Text)
            cmd.Parameters.AddWithValue("@Country", txtCountry.Text)
            cmd.Connection = con
        End Using
    End Using
End Sub
The Form
Using Parameterized queries to prevent SQL Injection Attacks in SQL Server
Record after Insert in database
Using Parameterized queries to prevent SQL Injection Attacks in SQL Server