How to Execute a SQL Query Using JDBC? Last Updated : 28 Apr, 2025 Summarize Comments Improve Suggest changes Share Like Article Like Report 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 JDBCWe 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 StatementUsing PreparedStatement Statement in JDBCThe 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 JDBCThe 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. Comment More infoAdvertise with us Next Article Java Tutorial E eswarbe06sp Follow Improve Article Tags : Java Java Programs JDBC Java Examples Practice Tags : Java Similar Reads Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s 10 min read Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it, 13 min read Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per 15+ min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me 15+ min read Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac 15+ min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an 13 min read Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt 10 min read Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its 8 min read Like