PARAMETERIZED QUERIES

SQL query parameterization

intro

As you may know, databases store and organize data in structures that are then accessed by SQL queries. In databases, we store valuable and sensitive information such as personal data or financial records, which makes our databases and the data within them a prime target for attackers.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT
PostgreSQL logo POSTGRESQL
THE POSTGRESQL DATABASE

One of the top attacks on databases is an SQL injection attack. An SQL injection attack occurs when an attacker modifies an SQL query, allowing the attacker to access sensitive information stored in the database.

To prevent an SQL injection attack, you can use database security practices such as parameterizing SQL queries and not providing user input straight into a database. A parameterized query is a query in which placeholders are used for parameters, and the parameter values are supplied at execution time.

Apart from preventing SQL injection attacks, parameterized SQL queries can help you reuse SQL queries, especially when performing repetitive tasks. Reusing SQL queries saves time and effort spent coding, allowing you to focus on important things such as extracting meaningful insights from the data.

In this tutorial, you will learn how to parameterize SQL queries to prevent SQL injection attacks and to make your SQL queries reusable.

Prerequisites

To follow along with this tutorial, you will need the following:

  • DbVisualizer, a database SQL client installed on your local machine. To install DbVisualizer, navigate to the DbVisualizer download page. Then, download the recommended installer for your operating system. After that, execute the installer you downloaded and follow the instructions.
  • A database management system. In this case, we will use Postgres. To install PostgreSQL, navigate to the PostgreSQL download page and download it for your operating system. You can follow this guide to install PostgreSQL on Windows, this guide to install it on Linux, and this guide to install it on macOS.
  • A basic understanding of SQL syntax and database management.

Connecting Postgres to DbVisualizer

Step 1: Start DbVisualizer and click Create a Connection button as shown below.

Creating a connection in DbVisualizer.
Creating a connection in DbVisualizer.

Step 2: Search for Postgres and double-tap the Postgres driver from the popup menu on the left side of your screen, as shown below.

Searching for the Postgres Driver in DbVisualizer.
Searching for the Postgres Driver in DbVisualizer.

An object view tab for the Postgres connection is opened.

The PostgreSQL connection Object View Tab
The PostgreSQL connection Object View Tab

Step 3: Fill in the database connection name field with “ParameterizeQuery,” as shown below.

Filling the Database Connection Name Field in DbVisualizer.
Filling the Database Connection Name Field in DbVisualizer.

Fill in the Database Userid field with “postgres” and the Database Password field with your password (we use “test123”) as shown below.

Filling the Authentication Tab in DbVisualizer.
Filling the Authentication Tab in DbVisualizer.

Once done, click the Connect button at the bottom, and if there are any issues, they will be displayed under the Connection Message section.

Postgres Connection Success Message in DbVisualizer.
Postgres Connection Success Message in DbVisualizer.

If the connection is successful, you should see the newly created ParameterizeQuery connection on the left sidebar of your screen.

Parameterizing Queries In SQL To Prevent SQL Injection Attacks

Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a web application by making the query and user input separate.

For example, consider a web application that requires users to enter a Username and Password to login into their accounts. When a user enters a username and password on the login form, the query below is executed on the database.

Copy
        
1 SELECT * FROM users WHERE username = '<username>' AND password = '<password>';

If the user input from the login form is not validated correctly, an attacker can exploit this SQL query and gain unauthorized access to your web application. If user input is parameterized, the query and the data are sent to the database separately.

Now, we will show you how to prevent SQL injection by parameterizing a query using DbVisualizer. Parameterizing a query helps deny attackers the ability to gain unauthorized access by injecting additional conditions into an SQL statement.

Parameterizing Queries in DbVisualizer

Step 1: Navigate to this Google Drive Link and download a web application user’s login dataset.

A web application users login dataset
A web application user's login dataset

Step 2: Open the database connection ParameterizeQuery on DbVisualizer. Right-click the Tables tab tree and select Import Table Data as shown below.

Selecting the Import Table Data Option in DbVisualizer.
Selecting the Import Table Data Option in DbVisualizer.

Step 3: Open the web application user’s login dataset file through the window that opens up.

Opening a File in DbVisualizer
Opening a File in DbVisualizer

Step 4: Keep clicking the Next button below the popup window until you reach the window below where you need to create a New Database Table.

Creating a New Database Table in DbVisualizer.
Creating a New Database Table in DbVisualizer.

Step 5: In the popup window, give the table that will hold the user’s login dataset a name. In this case, I have named my table users as shown below.

Giving a Table a Name in DbVisualizer.
Giving a Table a Name in DbVisualizer.

Step 6: Click the Next button and then import the dataset into your PostgreSQL database. If the data is imported successfully, you will get a Success message as shown below.

Successful Data Import in DbVisualizer.
Successful Data Import in DbVisualizer.

Step 7: Considering a simple login form where a user enters their username and password, the query below will compare the user’s input values with the values stored in the database. If they match, the user is granted access.

Copy
        
1 SELECT * FROM users WHERE username = '<username>' AND password = '<password>';

However, if an attacker enters **' ' OR '1'='1'** as the username and **0 or 1=1** as the password, they can gain access to your web application without using correct login credentials.

Copy
        
1 SELECT * FROM users WHERE username = '' OR '1'='1' AND password = 0 or 1=1;

To confirm if this is true, open an SQL editor in DbVisualizer using the (Ctrl+T) keys and execute the query above using the (Ctrl+Enter)  keys.

SQL injection attack
SQL injection attack

As a result, the query returns all rows from the users' table, granting the attacker unauthorized access.

Step 8: Using DbVisualizer, we can add variables or parameter markers to the query validating users' inputs on the login form to express that certain parts of the query should be replaced with values when the SQL is executed.

In this case, you can insert variables for the username and password as shown below to ensure that user-supplied values are treated as data and not executable code.

Copy
        
1 SELECT * FROM users WHERE username = '${Username}$' AND password = ${Password}$;

For that reason, if you execute the query, you will be prompted to enter a username and password.

Entering user credentials on value fields in DbVisualizer
Entering user credentials on value fields in DbVisualizer

If you try injecting SQL in the values fields, you get an error message hence denying you access if you are an attacker.

Error message in DbVisualizer If you try injecting SQL in the values fields
Error message in DbVisualizer If you try injecting SQL in the values fields

If you enter values that already exist in the users' table, you are granted access.

Getting access If you enter values that already exist in the users table
Getting access If you enter values that already exist in the users' table

Parameterizing Queries In SQL For Code Reusability

Assume you have been tasked by a company with thousands of employees to add the employees’ personal information into the company’s database. That means you will need to create an Employees table in the database first and then insert each employee’s information into the table.

To avoid the tedious process of repetitively adding each employee’s information, you can parameterize the INSERT INTO query and reuse it every time you add a different employee's information by following the steps below.

Step 1: Open the SQL editor in DbVisualizer using the (Ctrl+T) keys and create a table called Employees by executing the query below.

Copy
        
1 CREATE TABLE Employees ( 2 ID int, 3 First_Name varchar(255), 4 Last_Name varchar(255), 5 Address varchar(255), 6 City varchar(255) 7 );

Once the query is executed, you should get a success message that the Employees table was created.

Creating Employees table in DbVisualizer
Creating Employees table in DbVisualizer

Step 2: Use DbVisualizer parameter markers to parameterize a query that inserts each employee's information into the Employees table.

Copy
        
1 INSERT INTO employees (ID, First_Name, Last_Name, Address, City) 2 values (null, &FirstName, &LastName, &Address, &City);

Step 3: To insert an employee’s information into the Employees table, execute the query above using the (Ctrl+Enter)  keys and you will be prompted to insert the values.

Prompt to insert values into Employees table
Prompt to insert values into Employees table

Step 4: Let us say one of the company’s employee name is John Doe, whose address is 119 Bedford St. Lake Jackson, TX 77566. Below is how you would enter data for parameter markers. Then click the continue button to insert the employee's information into the Employees table.

Entering data for parameter markers in DbVisualizer
Entering data for parameter markers in DbVisualizer

Step 5: Open the Employees table and you should see that John Doe information was added.

Confirming employees information was added to the database
Confirming employee’s information was added to the database

Conclusion

In conclusion, learning to use parameterized SQL queries is crucial for keeping your data safe and efficiently managing databases. It guards against attacks like SQL injection and allows you to reuse queries.

By following this tutorial and utilizing tools like DbVisualizer, you'll enhance security and productivity, making your database work more effectively and worry-free.

We hope that you’ve enjoyed this tutorial and that you will stick around our blog for more tutorials to come.

FAQ

What is SQL query parameterization?

SQL query parameterization is a technique for separating user input from the SQL query itself. This helps to protect against SQL injection attacks by preventing malicious code from being injected into the query.

How does SQL query parameterization work?

Instead of embedding user input directly into the SQL query string, parameterized queries use placeholders to represent the user input. When the query is executed, the user input is passed to the database separately from the query itself. The database then substitutes the user input into the placeholders, creating a secure and validated query.

Why is SQL query parameterization important?

SQL injection attacks are a severe security risk that can lead to unauthorized access to data, data corruption, and even financial fraud. Using parameterized queries can significantly reduce your risk of being affected by a SQL injection attack.

Can parameterized queries be used with all database systems?

Yes, the concept of SQL query parameterization is applicable to most relational database systems, including but not limited to MySQL, PostgreSQL, SQL Server, and SQLite.

Dbvis download link img
About the author
Bonnie
Bonnie
Bonnie is a web developer and technical writer creating easy-to-understand technical articles.
The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

Digging Deeper into Advanced SQL Window Functions

author Ochuko Onojakpor tags 8 min 2025-01-16
title

OLTP vs OLAP: Comparing the Two Data Processing Systems

author Antonello Zanini tags Database system OLAP OLTP 9 min 2025-01-15
title

Automating SQL Queries with SQL CLI and SQL Job Scheduling

author Bonnie tags AUTOMATION SQL 6 min 2025-01-14
title

A Guide to SQL Server Indexes on Partitioned Tables

author Antonello Zanini tags SQL SERVER 7 min 2025-01-13
title

What Is the Pinecone Vector Database?

author Lukas Vileikis tags Data Visualization Tools DbVisualizer Search 6 min 2025-01-09
title

How to Display All Duplicate Records in a MySQL Table

author Antonello Zanini tags MySQL 6 min 2025-01-08
title

Understanding the SQL UNIQUE Constraint

author Leslie S. Gyamfi tags DbVisualizer SQL 6 min 2025-01-07
title

How to Drop an Index By Partition Number in SQL Server

author Antonello Zanini tags SQL SERVER 7 min 2025-01-06
title

Exploring Cursors and Temporary Tables in SQL

author Ochuko Onojakpor tags Cursors SQL 10 min 2024-12-30
title

The Most Interesting Functions in MySQL – A Guide

author Lukas Vileikis tags MySQL 5 min 2024-12-27

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.