How to Execute a SQL Query with Named Parameters in JDBC?
Last Updated :
09 Apr, 2024
Executing the SQL (Structured Query Language) query with named parameters in JDBC (Java Database Connectivity) is the fundamental feature of the database interaction in Java. Named parameters provide convenient and it provides a secure way to pass the values into the SQL queries without using concatenating the strings against attacks of SQL injection. While JDBC does not support the named parameters, we can achieve the same functionalities using the prepared statements.
Note: The Named parameters are emulated using placeholders like "?"
in prepared statements.
Prerequisites:
The following are the prerequisites to execute an SQL query with named parameters in JDBC.
- Java Development Kit (JDK)
- JDBC Driver (Java Database Connectivity)
- Database Connection
- Prepared Statement
Step-by-step implementation to execute a SQL query with named parameters in JDBC
Below is the step-by-step implementation to execute SQL query with Named Parameters in JDBC.
Step 1: Create a table in the Database.
Create a table in the database and name it as "login" and column names as "uname" and "password". Insert the rows into the table. Here is the example for "login" table:

Step 2: Create Java Project in Eclipse.
Open Eclipse IDE and create a Java project, name it as "JDBCExample".
Step 3: Add MYSQL JDBC Driver to the project.
- First download the MYSQL JDBC driver (jar file) from the MYSQL website.
- Open Eclipse, right click on the name of the project in the Package Explorer.
- After that, select the Build Path and then Configure Build Path.
- There is Libraries tab and then click Add External JARs and then select the downloaded MYSQL JDBC driver JAR file.
- After that, click Apply and then Apply and close button.
Here is the path for MYSQL JDBC driver jar file:

Step 4: Create a java class in Java project.
Create a class in the src folder in java project, and name it as "NamedParameterExample". Here is the path for java class file:

Step 5: Implement the code
Open the java class file and write the below code to execute a SQL query with named parameters in JDBC.
Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class NamedParameterExample
{
public static void main(String[] args)
{
// Database connection parameters
String url = "jdbc:mysql://localhost:3307/work"; //url for the database
String username = "root"; // username of database
String password = "tiger"; // password of database
// SQL query with named parameters
String sql = "SELECT * FROM login WHERE uname = ? AND password = ?";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn.prepareStatement(sql)) {
// Set parameter values using placeholder
stmt.setString(1, "jagan");
stmt.setString(2, "jaggu123");
// Execute the query
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
// Process the result set
// For example:
String column1Value = rs.getString("uname");
String column2Value = rs.getString("password");
System.out.println( " uname : " + column1Value + ", password: " + column2Value);
// ...
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Explanation of the above Program:
- In the above project, we established the connection to the database with the help of "DriverManager.getConnection ()".
- We have created the "PreparedStatement" using the SQL query.
- Then, we set the parameter values with the help of "setString()" method with using the parameter name as the first argument.
- Now, we will execute the query using the "executeQuery()" method.
Note: Ensure that you should replace the connection parameters such as URL, username, password with your details of the database connections. And replace the SQL query and parameters names with the your query and parameter names.
Step 6: Run the code
- Right click on the java class file and select Run As > Java Application.
- After running the code, the output will be shown in the console window in eclipse as shown below.
Output:
After running the java application, we can see the below output in console.
Similar Reads
How to Parameterize an SQL Server IN clause SQL Server IN Clause is used to filter data based on a set of values provided. The IN clause can be used instead of using multiple OR conditions to filter data from SELECT, UPDATE, or DELETE query. The IN clause with parameterized data mainly inside Stored Procedures helps filter dynamic data using
5 min read
How to Use Reserved Words as Column Names in SQL? In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL. But, there is an exception to this rule too. In this article, we will discuss how to use Reserved Words as column names in SQL. For this article, we
2 min read
How to Commit a Query in JDBC? COMMIT command is used to permanently save any transaction into the database. It is used to end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle Database treats as a single unit. This statement also erases
5 min read
How to Execute SQL Server Stored Procedure in SQL Developer? A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again.
2 min read
Executing SQL query with Psycopg2 in Python In this article, we are going to see how to execute SQL queries in PostgreSQL using Psycopg2 in Python. Psycopg2 is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with t
2 min read
How to Execute Multiple SQL Commands on a Database Simultaneously in JDBC? Java Database Connectivity also is known as JDBC is an application programming interface in Java that is used to establish connectivity between a Java application and database. JDBC commands can be used to perform SQL operations from the Java application. Demonstrating execution of multiple SQL comm
6 min read
How to Insert Records to a Table using JDBC Connection? Before inserting contents in a table we need to connect our java application to our database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the appl
4 min read
How to Escape a Single Quote in SQL Server? SQL stands for structured query language and is used to query databases for analytical needs. While using arithmetic queries, some results require strings to help them understand better. Strings can be formed by enclosing text in quotes. However in a case when quotes are themselves required in a str
4 min read
SQL Query to Get Column Names From a Table SQL stands for Structured Query Language. It is a language used to interact with the database, i.e to create a database, to create a table in the database, to retrieve data or update a table in the database, etc. SQL is an ANSI(American National Standards Institute) standard. Using SQL, we can do ma
2 min read
How to Declare a Variable in SQL Server? In SQL Server, variables play a critical role in the dynamic execution of SQL scripts and procedures. Variables allow you to store and manipulate data temporarily within the scope of a batch or procedure. By using the DECLARE statement, you can create variables with specific data types, which can th
6 min read