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.
Database
I have made use of the following table Customers with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of:
TextBox – For inputting Name and Country.
Button – For submitting the Form.
<table>
<tr>
<td>Name</td>
<td><asp:TextBoxID="txtName"runat="server" /></td>
</tr>
<tr>
<td>Country</td>
<td><asp:TextBoxID="txtCountry"runat="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:ButtonID="btnSubmit"Text="Submit"runat="server"OnClick="Submit" /></td>
</tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
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.
C#
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.Parameters.AddWithValue("@Country",txtCountry.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Response.Redirect(Request.Url.AbsolutePath);
}
VB.Net
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
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Response.Redirect(Request.Url.AbsolutePath)
End Sub
Screenshots
The Form
Record after Insert in database
Downloads