Day 9JDBC - 3
Day 9JDBC - 3
Day 9JDBC - 3
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.
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();
int i=stmt.executeUpdate();
System.out.println(i+" records updated");
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
Example of PreparedStatement interface that retrieve the records of a table
a column of a table
Entire table
a row of a table
None
9
Java CallableStatement Interface
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?
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:
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