How to Execute a SQL Query Using JDBC?
Last Updated :
28 Apr, 2025
Java programming provides a lot of packages for solving problems in our case we need to execute SQL queries by using JDBC. We can execute a SQL query in two different approaches by using PreparedStatement and Statement. These two interfaces are available in java.sql package. When comparing both of them the PreparedStatement approach is secure.
Approaches to Execute a SQL Query using JDBC
We have two different approaches to executing a SQL query using JDBC. Below is the list and we will explain them with examples to understand the concept correctly.
- Using Statement
- Using PreparedStatement
Statement in JDBC
The Statement is an interface that is available in java.sql package with JDBC.
- This interface is part of JDBC API and can execute simple SQL queries without parameters.
- We can create a Statement by using createStatement().
- This method is available in the Connection class.
Example:
In this example, we will write an SQL query to fetch all data from the table in the database. We have already some data in the table. Now we will write an SQL query for fetching that data using Statement.
For this, we have used a database named books and the table name is a book.
Java
package geeksforgeeks;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrieveDataExample {
public static void main(String[] args) {
try {
// load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// establish connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/books", "root", "password");
if (con != null) {
// SQL query to retrieve data from the 'book' table
String selectQuery = "SELECT * FROM book";
Statement statement = con.createStatement();
// execute the query and get the result set
ResultSet resultSet = statement.executeQuery(selectQuery);
System.out.println("The Available Data\n");
// iterate through the result set and print the data
while (resultSet.next()) {
int id = resultSet.getInt("id");
String author_name = resultSet.getString("author");
String book_name = resultSet.getString("name");
String book_price = resultSet.getString("price");
// print the retrieved data
System.out.println("ID: " + id + ", Author_Name: " + author_name + ", Book_Name: " + book_name
+ ", Book_Price " + book_price);
}
} else {
System.out.println("Not Connected...");
}
} catch (Exception e) {
// handle any exceptions that occur
System.out.println("Exception is " + e.getMessage());
}
}
}
Output:
Below we can see the retrieved data in book table.

Explanation of the Code:
- We fetched all data from book table from books database by using SQL query.
- First, we need to connect the database by using required configuration.
- After that create Statement by using createStatement() from connection object.
- After that write SQL query for fetch all data.
- Now Create ResultSet for this assign the result of SQL query.
- Then print that data by using loop statement.
PreparedStatement in JDBC
The PreparedStatement is an interface, and it provides for security for our data by using parameter concept in Java.
- It can prevent SQL Injection attack also from unknown source.
- It is better than Statement.
- We can create PreparedStatement by using prepareStatement() from connection class and it can take SQL query as String value.
Example:
Java
package geeksforgeeks;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class RetrieveDataExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/books", "root", "password");
if (con != null) {
String selectQuery = "SELECT * FROM book";
PreparedStatement statement = con.prepareStatement(selectQuery);
ResultSet resultSet = statement.executeQuery();
System.out.println("The Available Data\n");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String author_name = resultSet.getString("author");
String book_name = resultSet.getString("name");
String book_price = resultSet.getString("price");
System.out.println("ID: " + id + ", Author_Name: " + author_name + ", Book_Name: "
+ book_name + ", Book_Price "+book_price);
}
} else {
System.out.println("Not Connected...");
}
} catch (Exception e) {
System.out.println("Exception is " + e.getMessage());
}
}
}
Output:

Explanation of the above Code:
- First, we have created Connection with Database by using required configuration.
- Then we have created PreparedStatement by using con.prepareStatement(selectQuery).
- Here selectQuery is the String which is required SQL query for fetching all records from table.
- After that we have created one ResultSet then assign this SQL query result to It.
- After that it display data by using ResultSet object with the help of loop statement.
Similar Reads
How to Execute a SQL Script File using JDBC? JDBC stands for Java Database Connectivity. It is an API (Application Programming Interface) that allows developers to connect their Java code to any SQL database instance. The connection gives the power to developers to execute any SQL queries, be it creating, updating, or data retrieving queries,
6 min read
How to Execute a SQL Query with Pagination in JDBC? To execute a SQL query with pagination in JDBC (Java Database Connectivity), normally we use SQL syntax to limit the number of rows returned and then iterate through the results as per the need. We often use SQL's LIMIT and OFFSET clauses to execute page SQL queries in JDBC. Steps to Execute SQL Que
3 min read
How to Execute a SQL Query with Named Parameters in JDBC? 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 concat
4 min read
How to Extract Database Metadata using JDBC? In JDBC, for extracting Metadata from the database we have one interface which is DatabaseMetaData. By using this interface, we can extract the metadata from the Database. We have a connection object It has getMetaData() method. After this, define the DatabaseMetaData and create an object for this.
8 min read
How to Perform a Bulk Insertion using JDBC? Performing a bulk insert using JDBC involves using the PreparedStatement interface and addBatch() method. This addBatch() method increases the performance while data is inserted into a database. In this article, we will learn how to perform a bulk insert using JDBC. Approach:For this, we need to cre
4 min read
How to Create, Edit & Alter Tables Using Java? In Java, JDBC can be used to create, edit, and alter the tables. JDBC can be defined as Java Database Connectivity. It is an API that allows Java programs to interact with the databases. JDBC can implement Java programs to execute SQL queries and manipulate databases through a standard interface. In
5 min read
How to Get the Datatype of a Column of a Table using JDBC? Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. MySQL: mysql-connector-java-8.0.22 or similar mysql connectors with different versions. In this article, we are using mysql-connector-java-8
5 min read
How to Handle NULL Values in JDBC? Java programming can be able to handle databases by using JDBC API. In this article, we will discuss how to handle NULL values in JDBC. For this problem, we have inserted some data into an already created table named book in my Database named books. To handle null values in JDBC involves checking fo
4 min read
How to add Image to MySql database using Servlet and JDBC Structured Query Language or SQL is a standard Database language which is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will understand how to add an image to the MYSQL database using servlet. MYSQL is a rel
6 min read