Day 9JDBC - 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 17

Lecture Objectives

In this lecture, we will discuss:


• Working with statements

1
Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

Commonly used methods of Statement interface:


The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
Example of Statement interface

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();

//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");


//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}
PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute


parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.

Why use PreparedStatement?


Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:


import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Example of PreparedStatement interface that updates the record

PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");


stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);

int i=stmt.executeUpdate();
System.out.println(i+" records updated");

Example of PreparedStatement interface that deletes the record

PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");


stmt.setInt(1,101);

int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
Example of PreparedStatement interface that retrieve the records of a table

PreparedStatement stmt=con.prepareStatement("select * from emp");


ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
MCQ
The object of ResultSet maintains a cursor pointing to

a column of a table
Entire table
a row of a table
None

9
Java CallableStatement Interface

CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you
may create a function that receives date as the input and returns age of the
employee as the output.
Difference between stored procedures and functions.
How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of CallableStatement.

Syntax is given below:


public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:


CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure myprocedure that receives 2 arguments.

12
Full example to call the stored procedure using JDBC
To call the stored procedure, you need to create it in the database. Here, we are assuming that stored procedure
looks like this.
create or replace procedure "INSERTR"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user12 values(id,name);
end;
/
The table structure is given below:
create table user12(id number(10), name varchar2(200));
In this example, we are going to call the stored procedure INSERTR that receives id and name as the parameter
and inserts it into the table user12. Note that you need to create the user12 table as well to run this
application. 13
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();
System.out.println("success");
}
}

Now check the table in the database, value is inserted in the user12 table.
14
Summary:

In this session, you were able to :


• Learn about Introduction to Streams
• Understand Java FileOutputStream Class
References:
Books:
1. Balaguruswamy, Java.
2. A Primer, E.Balaguruswamy, Programming with Java, Tata McGraw Hill
Companies
3. John P. Flynt Thomson, Java Programming.

Video Lectures :
https://youtu.be/eEqPrlu28Sc

Reference Links:

https://www.tutorialspoint.com/jdbc/jdbc-statements.htm
https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html
https://www.javatpoint.com/Statement-interface
https://www.javatpoint.com/PreparedStatement-interface
https://www.javatpoint.com/CallableStatement-interface
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy