0% found this document useful (0 votes)
33 views

Statement Types

There are three types of Statement objects in JDBC: 1. Statement - Used for simple SQL statements without parameters 2. PreparedStatement - Used for precompiled SQL statements with or without IN parameters 3. CallableStatement - Used to execute calls to database stored procedures

Uploaded by

Hari Chandrudu M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Statement Types

There are three types of Statement objects in JDBC: 1. Statement - Used for simple SQL statements without parameters 2. PreparedStatement - Used for precompiled SQL statements with or without IN parameters 3. CallableStatement - Used to execute calls to database stored procedures

Uploaded by

Hari Chandrudu M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Types of Statements in JDBC

A Statement object sends SQL statements to a database. There are three kinds of Statement
objects. Each is specialized to send a particular type of SQL statement:

 A Statement object is used to execute a simple SQL statement with no parameters.


 A PreparedStatement object is used to execute a precompiled SQL statement with
or without IN parameters.
 A CallableStatement object is used to execute a call to a database stored procedure.

1.  Create a Statement: From the connection interface, you can create the object for this
interface. It is generally used for general–purpose access to databases and is useful while
using 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 Program illustrating Create Statement in JDBC

// Importing Database(SQL) classes


import java.sql.*;

// Class
class Sample {

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

2. Prepared Statement represents a recompiled SQL statement, that can be executed many
times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED STATEMENT
at run time.

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(?, ?)";


Statement 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 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 Sampledb{

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

3. Callable Statement are stored procedures which are a group of statements that we compile
in the database for some task, they are beneficial when we are dealing with multiple tables
with complex scenario & rather than sending multiple queries to the database, we can send
the required data to the stored procedure & lower the logic executed in the database server
itself. The Callable Statement interface provided by JDBC API helps in executing stored
procedures.

Syntax: To prepare a CallableStatement

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

Implementation: Once the callable statement object is created

 execute() is used to perform the execution of the statement.

Example:
// Java Program illustrating Callable Statement in JDBC

// Step 1: Importing DB(SQL) classes


import java.sql.*;

// Main class
class Sampledb1{

// Main driver method


public static void main(String[] args)
{
// Try block to check if any exceptions occurs
try {

// Step 2: Establish a connection

// Step 3: 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 4: Create a statement


Statement s = con.createStatement();

// Step 5: Execute the query


// select * from people

CallableStatement cs = con.prepareCall("{call peopleinfo(?,?)}");


cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result = s.executeQuery("select * from people");

// Step 6: Process the results

// Condition check using next() method


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

// Print and display elements (Name and Age)


System.out.println("Name : " + result.getString(1));
System.out.println("Age : "+ result.getInt(2));
}
}

// Catch statement for DB exceptions


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catch block for generic class exceptions


catch (ClassNotFoundException e) {

// Print the line number where exception occurred


e.printStackTrace();
}
}
}
 
JDBC ResultSet Interface

ResultSet Interface is present in the java.sql package. It is used to store the data which are
returned from the database table after the execution of the SQL statements in the Java
Program. The object of ResultSet maintains cursor point at the result data. In default, the
cursor positions before the first row of the result data.

The next() method is used to move the cursor to the next position in a forward direction. It
will return FALSE if there are no more records. It retrieves data by calling the
executeQuery() method using any of the statement objects. It may be Statement or
PreparedStatement or CallableStatement object. PreparedStatement, and CallableStatement
interfaces are the sub-interfaces of the Statement interface.
Statement Interface

Statement statemnt1 = conn.createStatement();


ResultSet rs1 = statemnt1.executeQuery(“Select * from EMPLOYEE_DETAILS”);

PreparedStatement Interface

PreparedStatement pstatemnt1 = conn.prepareStatement(insert_query);


ResultSet rs1 = pstatemnt1.executeQuery(“Select * from EMPLOYEE_DETAILS”);

We can use getX() method to get the data of the columns while iterating through the results
where X – is the datatype of the column. We can use either Column Names or Index to get
the values using getX() methods.

while(rs1.next())

    int empNum = rs1.getInt("empNum");

    String lastName = rs1.getString("lastName");

    String firstName = rs1.getString("firstName");

    String email = rs1.getString("email");

    String deptNum = rs1.getString("deptNum");

    String salary = rs1.getString("salary");

    System.out.println(empNum + "," +lastName+ "," +firstName+ "," +email


+","+deptNum +"," +salary);

We can also mention index number of the Column instead of Column Name in the getX()
methods.

while(rs1.next())

    int empNum = rs1.getInt(1);

    String lastName = rs1.getString(2);

    String firstName = rs1.getString(3);

    String email = rs1.getString(4);

    String deptNum = rs1.getString(5);

    String salary = rs1.getString(6);

    System.out.println(empNum + "," +lastName+ "," +firstName+ "," +email


+","+deptNum +"," +salary);

}
ResultSet Types

In default, we can iterate the data/values in ResultSet which have returned as an output of the
executed SQL statement in the forward direction. We can iterate the values in other directions
using Scrollable ResultSet. We can specify the type and concurrency of ResultSet while
creating Statement, PreparedStatement, and CallableStatement objects.

There are 3 types in ResultSet. They are:

1. TYPE_FORWARD_ONLY: It is the default option, where the cursor moves from start to end
i.e. in the forward direction.
2. TYPE_SCROLL_INSENSITIVE: In this type, it will make the cursor to move in both forward and
backward directions. If we make any changes in the data while iterating the stored data it
won’t update in the dataset if anyone changes the data in DB. Because the dataset has the
data from the time the SQL query returns the Data.
3. TYPE_SCROLL_SENSITIVE: It is similar to TYPE_SCROLL_INSENSITIVE, the difference is if
anyone updates the data after the SQL Query has returned the data, while iterating it will
reflect the changes to the dataset.

ResultSet Concurrency

There are 2 modes of Concurrency in ResultSet. They are:

1. ResultSet.CONCUR_READ_ONLY: It is the default concurrency mode. We can only read the


data in the ResultSet. Updation is not applicable.
2. ResultSet.CONCUR_UPDATABLE: We can update the data in the ResultSet object.

Some databases don’t support concurrency mode for all ResultSet types. In that case, we need
to check whether they support our desired type and concurrency mode using
supportsResultSetConcurrency() method.

Methods In ResultSet Interface

There are 4 categories of ResultSet methods. They are:

1. Navigational Methods
2. Getter Methods
3. Setter Methods
4. Miscellaneous Methods

First, we will discuss the Navigational Methods and then will move further.

#1) Navigational Methods

This method is used to move the cursor around the dataset.

 Boolean absolute(int row): It is used to move the cursor to the specified row which is
mentioned in the parameter and return true if the operation is successful else return false.
 Void afterLast(): It makes the ResultSet cursor to move after the last row.
 Void beforeFirst(): It makes the ResultSet cursor to move before the first row.
 Boolean first(): It makes the ResultSet cursor to move to the first row. It returns True if the
operation is successful else False.
 Boolean last(): It makes the ResultSet cursor to move to the last row. It returns True if the
operation is successful else False.
 Boolean next(): It makes the ResultSet cursor to move to the next row. It returns True if
there are more records and False if there are no more records.
 Boolean previous(): It makes the ResultSet cursor to move to the previous row. It returns
True if the operation is successful else False.
 Boolean relative(): It moves the cursor to the given number of rows either in the forward or
backward direction.
 Int getRow(): It returns the current row number the ResultSet object is pointing now.
 Void moveToCurrentRow(): It moves the cursor back to the current row if it is currently in
insert row.
 Void moveToInsertRow(): It moves the cursor to the specific row to insert the row into the
Database. It remembers the current cursor location. So we can use the moveToCurrentRow()
method to move the cursor to the current row after the insertion.

You might also like