Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Types of Statements in JDBC
Next article icon

Types of Statements in JDBC

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the Statement interface in JDBC (Java Database Connectivity) is used to create and execute SQL queries in Java applications. JDBC provides three types of statements to interact with the database:

  • Statement
  • Prepared Statement
  • Callable Statement

1. Statement

A Statement object is used for general-purpose access to databases and is useful for executing static SQL statements at runtime.

Syntax:

Statement statement = connection.createStatement();

Implementation: Once the Statement object is created, there are three ways to execute it.

  • execute(String SQL): It is used to executes any SQL statements (like SELECT, INSERT, UPDATE or DELETE). If the ResultSet object is retrieved, then it returns true else false is returned.
  • executeUpdate(String SQL): It is used to executes SQL statements (like INSERT, UPDATE or DELETE). It returns the number of rows affected by the SQL statement.
  • ResultSet executeQuery(String SQL): It is used to executes the SELECT query. It returns a ResultSet object that contains the data retrieved by the query.

Example:

Java
// Java Program illustrating Create Statement in JDBC import java.sql.*;  public class Geeks {     public static void main(String[] args) {         try {                        // Load the driver             Class.forName("com.mysql.cj.jdbc.Driver");              // Establish the connection             Connection con = DriverManager.getConnection(                 "jdbc:mysql://localhost:3306/world", "root", "12345");              // Create a statement             Statement st = con.createStatement();              // Execute a query             String sql = "SELECT * FROM people";             ResultSet rs = st.executeQuery(sql);              // Process the results             while (rs.next()) {                 System.out.println("Name: " + rs.getString("name") +                                    ", Age: " + rs.getInt("age"));             }              // Close resources             rs.close();             st.close();             con.close();         } catch (Exception e) {             e.printStackTrace();         }     } } 

Output: Name and age are as shown for random inputs.

Output of Create Statement

2. Prepared Statement

A PreparedStatement represents a precompiled SQL statement that can be executed multiple times. It accepts parameterized SQL queries, with ? as placeholders for parameters, which can be set dynamically.

Illustration: 

Considering in the people database if there is a need to INSERT some values, SQL statements such as these are used: 

INSERT INTO people VALUES ("Ayan",25);

INSERT INTO people VALUES("Kriya",32);

To do the same in Java, one may use Prepared Statements and set the values in the ? holders, setABC() of a prepared statement is used as shown: 

String query = "INSERT INTO people(name, age)VALUES(?, ?)";

PreparedStatement pstmt = con.prepareStatement(query);

// where pstmt is an object name

pstmt.setString(1,"Ayan");

ptstmt.setInt(2,25);

Implementation: Once the PreparedStatement object is created, there are three ways to execute it: 

  • execute(): This returns a boolean value and executes a static SQL statement that is present in the prepared statement object.
  • executeQuery(): This returns a ResultSet from the current prepared statement.
  • executeUpdate(): This returns the number of rows affected by the DML statements such as INSERT, DELETE, and more that is present in the current Prepared Statement.

Example: 

Java
// Java Program illustrating Prepared Statement in JDBC import java.sql.*;  import java.util.Scanner;  class Geeks {      public static void main(String[] args) {                // try block to check for exceptions         try {              // Loading drivers using forName() method             Class.forName("com.mysql.cj.jdbc.Driver");              // Scanner class to take input from user             Scanner sc = new Scanner(System.in);              System.out.println(                 "What age do you want to search?? ");              // Reading age an primitive datatype from user             // using nextInt() method             int age = sc.nextInt();              // Registering drivers using DriverManager             Connection con = DriverManager.getConnection(                 "jdbc:mysql:///world", "root", "12345");              // Create a statement             PreparedStatement ps = con.prepareStatement(                 "select name from world.people where age = ?");              // Execute the query             ps.setInt(1, age);             ResultSet res = ps.executeQuery();              // Condition check using next() method             // to check for element             while (res.next()) {                  // Print and display elements(Names)                 System.out.println("Name : "                                    + res.getString(1));             }          }          // Catch block to handle database exceptions         catch (SQLException e) {              // Display the DB exception if any             System.out.println(e);         }          // Catch block to handle class exceptions         catch (ClassNotFoundException e) {              // Print the line number where exception occurred             // using printStackTrace() method if any             e.printStackTrace();         }     } } 

Output: 

Output of Prepared Statement

3. Callable Statement

A CallableStatement is used to execute stored procedures in the database. Stored procedures are precompiled SQL statements that can be called with parameters. They are useful for executing complex operations that involve multiple SQL statements.

Syntax:

CallableStatement cstmt = con.prepareCall("{call ProcedureName(?, ?)}");

  • {call ProcedureName(?, ?)}: Calls a stored procedure named ProcedureName with placeholders ? for input parameters.

Methods to Execute:

  • execute(): Executes the stored procedure and returns a boolean indicating whether the result is a ResultSet (true) or an update count (false).
  • executeQuery(): Executes a stored procedure that returns a ResultSet.
  • executeUpdate(): Executes a stored procedure that performs an update and returns the number of rows affected.

Example:

Java
// Java Program illustrating  // Callable Statement in JDBC import java.sql.*;  public class Geeks {      public static void main(String[] args) {                // Try block to check if any exceptions occur         try {                        // Load and register the driver             Class.forName("com.mysql.cj.jdbc.Driver");              // Establish a connection             Connection con = DriverManager               .getConnection("jdbc:mysql:///world", "root", "12345");              // Create a CallableStatement             CallableStatement cs =                con.prepareCall("{call GetPeopleInfo()}");              // Execute the stored procedure             ResultSet res = cs.executeQuery();              // Process the results             while (res.next()) {                                // Print and display elements (Name and Age)                 System.out.println("Name : " + res.getString("name"));                 System.out.println("Age : " + res.getInt("age"));             }              // Close resources             res.close();             cs.close();             con.close();         }          // Catch block for SQL exceptions         catch (SQLException e) {             e.printStackTrace();         }          // Catch block for ClassNotFoundException         catch (ClassNotFoundException e) {             e.printStackTrace();         }     } } 

Output: 

Output for Callable Statement

Explanation:

  • This Java code demonstrates how to use a CallableStatement in JDBC to execute a stored procedure.
  • It connects to a MySQL database and prepares a CallableStatement to call a stored procedure named peopleinfo with two parameters.
  • After executing the procedure, it runs a SELECT query to retrieve and display all records from the people table.
  • Exception handling is included to manage potential SQL and class loading errors.

Next Article
Types of Statements in JDBC

B

budhirajachinab99
Improve
Article Tags :
  • Java
  • Technical Scripter
  • JDBC
Practice Tags :
  • Java

Similar Reads

    Spring - Prepared Statement JDBC Template
    In Enterprise applications, accessing and storing data in a relational database is a common requirement. Java Database Connectivity (JDBC) is an essential part of Java SE, and it provides a set of standard APIs to interact with relational databases in a way that is not tied to any database vendor. W
    6 min read
    How to Use PreparedStatement in Java?
    A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of Statement. Prepared Statement objects have some useful additional features than Statement objects. Instead of hard coding queries, PreparedStatement object provides a feature to execute a parameterized query. Advantages of
    3 min read
    JDBC - Type 3 Driver
    A JDBC driver enables Java application to interact with a database from where we can fetch or store data. JDBC drivers are analogous to ODBC drivers. The JDBC classes are contained in the Java Package java.sql and javax.sql.JDBC helps to Connect to a data source, like a database.Send queries and upd
    2 min read
    Hibernate - Types of Mapping
    Hibernate is a Java framework that simplifies the development of Java applications to interact with the database. It is an open-source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence. There are different r
    2 min read
    Spring - JDBC Template
    In this article, we will discuss the Spring JDBC Template and how to configure the JDBC Template to execute queries. Spring JDBC Template provides a fluent API that improves code simplicity and readability, and the JDBC Template is used to connect to the database and execute SQL Queries. What is JDB
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences