(Translated by https://www.hiragana.jp/)
Types of Statements in JDBC - GeeksforGeeks
Open In App

Types of Statements in JDBC

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Statement interface in JDBC is used to create SQL statements in Java and execute queries with the database. There are different types of statements used in JDBC:

  • Create Statement
  • Prepared Statement
  • Callable Statement

1.  Create a 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.

  • boolean execute(String SQL): If the ResultSet object is retrieved, then it returns true else false is returned. Is used to execute SQL DDL statements or for dynamic SQL.
  • int executeUpdate(String SQL): Returns number of rows that are affected by the execution of the statement, used when you need a number for INSERT, DELETE or UPDATE statements.
  • ResultSet executeQuery(String SQL): Returns a ResultSet object. Used similarly as SELECT is used in SQL.

Example:

Java
// Java Program illustrating Create Statement in JDBC

// Importing Database(SQL) classes
import java.sql.*;

// Class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Try block to check if any exceptions occur
        try {

            // Step 2: Loading and registering drivers

            // Loading driver using forName() method
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Registering driver using DriverManager
            Connection con = DriverManager.getConnection(
                "jdbc:mysql:///world", "root", "12345");

            // Step 3: Create a statement
            Statement statement = con.createStatement();
            String sql = "select * from people";

            // Step 4: Execute the query
            ResultSet result = statement.executeQuery(sql);

            // Step 5: Process the results

            // Condition check using hasNext() method which
            // holds true till there is single element
            // remaining in List
            while (result.next()) {

                // Print name an age
                System.out.println(
                    "Name: " + result.getString("name"));
                System.out.println(
                    "Age:" + result.getString("age"));
            }
        }

        // Catching database exceptions if any
        catch (SQLException e) {

            // Print the exception
            System.out.println(e);
        }

        // Catching generic ClassNotFoundException if any
        catch (ClassNotFoundException e) {

            // Print and display the line number
            // where exception occurred
            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, setXXX() of a prepared statement is used as shown: 

String query = "INSERT INTO people(name, age)VALUES(?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
// where pstmt is an object name

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(): Returns a ResultSet from the current prepared statement.
  • executeUpdate(): 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

// Step 1: Importing DB(SQL here) classes
import java.sql.*;
// Importing Scanner class to
// take input from the user
import java.util.Scanner;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // try block to check for exceptions
        try {

            // Step 2: Establish a connection

            // Step 3: Load and register drivers

            // 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);

            // Display message for ease for user
            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");

            // Step 4: Create a statement
            PreparedStatement ps = con.prepareStatement(
                "select name from world.people where age = ?");

            // Step 5: Execute the query
            ps.setInt(1, age);
            ResultSet result = ps.executeQuery();

            // Step 6: Process the results

            // Condition check using next() method
            // to check for element
            while (result.next()) {

                // Print and display elements(Names)
                System.out.println("Name : "
                                   + result.getString(1));
            }

            // Step 7: Closing the connections
            // (Optional but it is recommended to do so)
        }

        // 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: To create a CallableStatement,

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

// Importing DB(SQL) classes
import java.sql.*;

public class GFG {

    // Main driver method
    public static void main(String[] args) {
        // Try block to check if any exceptions occur
        try {
            // Step 1: Load and register the driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Step 2: Establish a connection
            Connection con = DriverManager.getConnection("jdbc:mysql:///world", "root", "12345");

            // Step 3: Create a CallableStatement
            CallableStatement cs = con.prepareCall("{call GetPeopleInfo()}");

            // Step 4: Execute the stored procedure
            ResultSet result = cs.executeQuery();

            // Step 5: Process the results
            while (result.next()) {
                // Print and display elements (Name and Age)
                System.out.println("Name : " + result.getString("name"));
                System.out.println("Age : " + result.getInt("age"));
            }

            // Step 6: Close resources
            result.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: 

Explanation of the Program:

  • 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.


Previous Article
Next Article

Similar Reads

Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 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 all save points in the transaction and releases t
5 min read
Simplifying CRUD Operation with JDBC
Creating, reading, updating, and deleting data in a database is a common task in many applications, and JDBC (Java Database Connectivity) is a Java API that allows you to connect to a database and perform these operations. In this blog post, we will walk through the steps of setting up a simple CRUD (create, read, update, delete) operation using JD
3 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 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 applications-to-JDBC connection and JDBC driver provid
4 min read
Java Program to Retrieve Contents of a Table Using JDBC connection
It can be of two types namely structural and non-structural database. The structural database is the one which can be stored in row and columns. A nonstructural database can not be stored in form of rows and columns for which new concepts are introduced which would not be discussing here. Most of the real-world data is non-structural like photos, v
5 min read
Delete Contents From Table Using JDBC
JDBC(Java Database Connectivity) is a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend(for storing data). Approach: 1. CREATE DATABASE: Create a database using sqlyog and create some tables in
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 commands on a database simultaneously using the addBat
6 min read
JDBC - Type 4 Driver
Let us do get a cover overview of the JDBC and the ODBC prior in order to better understand what exactly is type 4 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.JDB
3 min read
JDBC - Type 2 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 update statements to the databaseRetrieve and process
2 min read
JDBC - Type 1 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 update statements to the databaseRetrieve and process
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 update statements to the databaseRetrieve and process
2 min read
Inserting Records in Batch Using JDBC
It is carried out using the functions namely addBatch() and executeBatch() methods. For that lets us do have a prior understanding of JDBC drivers. So, in order to connect to your database in Java, you need a JDBC driver. Every database (MySQL, Oracle, etc.) comes with its own JDBC driver, usually built by the database vendor and found on the datab
2 min read
Spring - Prepared Statement JDBC Template
In Enterprise applications, data access/stored in relational databases is a common requirement. As an essential part of Java SE, Java Database Connectivity (JDBC) defines a set of standard APIs to access relational databases in a vendor-independent fashion. However, when using JDBC, the developer has to manage all database-related resources and han
5 min read
Java JDBC - Difference Between Row Set and Result Set
ResultSet characteristics are as follows: It maintains a connection to a database and because of that, it can’t be serialized.it can not pass the Result set object from one class to another class across the network.ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row. The
2 min read
Difference Between Connected vs Disconnected RowSet in Java JDBC
A RowSet is a wrapper around a ResultSet object. It can be connected, disconnected from the database, and can be serialized. It maintains a JavaBean component by setting the properties. You can pass a RowSet object over the network. By default, the RowSet object is scrollable and updatable. This diagram will give you more idea about ResultSet and R
5 min read
Servlet With JDBC
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Properties of Servlets are as follows: Servlets work on the server-side.Servlets are capable of handling
12 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Spring JDBC Example
JDBC or Java Database Connectivity is a specification from Sun microsystems that provides a standard abstraction(that is API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write programs required to access databases. JDBC along with the data
4 min read
Advantages of Spring Boot JDBC
Spring JDBC is used to build the Data Access Layer of enterprise applications, it enables developers to connect to the database and write SQL queries and update data to the relational database. The code related to the database has to be placed in DAO classes. SpringJDBC provides a class called JdbcTemplate to handle the database-related logic. Jdbc
3 min read
Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
We will be running the SQL scripts with Spring JDBC +JPA + HSQLDB. These scripts are used to perform SQL commands at the time of application start. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. JPA is just a specification that faci
3 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
JUnit - Sample Maven Project With JDBC
The quality of software should be of a high standard and then only it is liked and used by most people. A good programmer is one who prepares software error-free, JUnit helps us a lot in achieving that. In this article, let us see a MySQL database connecting with Java via JDBC, and the data is checked against JUnit. Example Maven Project Project St
6 min read
How to Call Stored Functions and Stored Procedures using JDBC?
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write pr
5 min read
Standard Steps to Be Followed For Developing JDBC Application
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write pr
4 min read
Working with Large Objects Using JDBC in Java
Sometimes as part of programming requirements, we have to insert and retrieve large files like images, video files, audio files, resumes, etc with respect to the database. Example: Uploading images on the matrimonial websiteUpload resume on job-related websites To store and retrieve large information we should go for Large Objects(LOBs). There are
5 min read
Spring Security - JDBC Authentication
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for Java applications to communicate with various databases. It provides the language with Java database connectivity standards. It is used to write pr
8 min read
Spring Data JDBC Extensions
In this article, We will explore the realm of Spring Data JDBC extensions. Discover how they enhance the functionalities of the Spring Data JDBC module. These extensions offer a range of tools that enable developers to handle database interactions, with skill-making tasks, like simplifying queries enhancing security, and optimizing performance mana
3 min read
Spring - JDBC Template
In this article, we will discuss about 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. JDBC (Java Database Connectivity) is an application programm
5 min read
Difference between ODBC and JDBC
JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity). These both are API standards used for connecting applications to databases. ODBC can be used by various programming languages as it is a general API standard. But JDBC is Java-specific and it provides a Java-based interface for database access. ODBC drivers are not Java-centri
2 min read
Article Tags :
Practice Tags :