You are on page 1of 75

Programming in Java

INTRODUCTION TO JDBC IN JAVA

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 1 of Resources Pvt. Ltd.
Programming in Java

Introduction to RDBMS
• RDBMS or relational database management system is a software
meant to store and maintain huge amount of data in a structured
form of rows and columns.
• RDBMS is based on relational model which maintains tables with
enforced relationships.
• RDBMS helps us to access records by multiple users.
• Examples: Oracle, MySQL, MS SQL Server, IBM DB2

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 2 of Resources Pvt. Ltd.
Programming in Java

Introduction to Database Connection

Before performing any operations on Database management system,


one need to establish a connection between application program and
DBMS software.

In platform dependent applications, the connectivity is established by


means of ODBC (Open Data Base Connectivity)

In platform independent applications written in Java, connectivity


between RDBMS and application is established using JDBC(Java
Data Base Connectivity)

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 3 of Resources Pvt. Ltd.
Programming in Java

JDBC
JDBC is a Java API that connects to a relational databases,

JDBC helps us to use DCL, DDL, DML and DQL languages of SQL to
operate on RDBMS

JDBC is not meant for a particular RDBMS. It is Database


independent

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 4 of Resources Pvt. Ltd.
Programming in Java
JDBC connectivity (contd)

Why Should We Use JDBC


• Before JDBC, ODBC API was the database API to connect and execute
the query with the database. But, ODBC API uses ODBC driver which
is written in C language (i.e. platform dependent and unsecured).

• Java has defined its own API (JDBC API) using JDBC drivers
(written in Java language). Hence JDBC achieves true platform
independence.

• The JDBC API supports communication between the Java


application and the JDBC manager.

• The JDBC driver supports communication between the JDBC


manager and the database driver.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 5 of Resources Pvt. Ltd.
Programming in Java
Data flow from Java application to database

JAVA applications

JDBC API

JDBC DB Driver

SQL languages & Data

Underlying RDBMS (Oracle, My SQL, Access etc.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 6 of Resources Pvt. Ltd.
Programming in Java
Scope of the tutorial
• We will see a step by step approach to connect Java application to a
database like MYSQL using JDBC.

• This tutorial covers important concepts of JDBC


• JDBC Driver
• Establishing Connection
• Statements
• ResultSet to retrieve data
• Batch Updates
• Transactions
• DatabaseMetaData

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 7 of Resources Pvt. Ltd.
Programming
Example in Java
to connect MySQL database
Before going deep inside the concepts of JDBC and connectivity between MySQL
database, we will see a sample program that illustrates various steps involved in
connectivity from Java application and RDBMS
 
import java.sql.*;   /* Creating query statement*/
class MysqlCon{   Statement stmt=con.createStatement();  
public static void main(String args[]) ResultSet rs=stmt.executeQuery("select * from 
{   emp");  
try{  
/* Extracting result from ResultSet */
/* Registering driver */ while(rs.next())  
Class.forName("com.mysql.jdbc.Driver");  System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"
  "+rs.getString(3));  
/* Establishing connection */ 
Connection con=DriverManager.getConnectio /* Close the connection */
n("jdbc:mysql://localhost:3306/ con.close();  
sys","root","root"); }
  catch(Exception e){ System.out.println(e);}  
/* Here localhost is the DB Server }  
Sys is the database, root and root are }  
credentials*/ 
  

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 8 of Resources Pvt. Ltd.
Programming in Java
DATABASE CREATION

Install or locate the database you want to access.

If MySQL is already installed in y0ur machine, Proceed with


creating database and tables in MySQL

Create Database
CREATE DATABASE is the SQL command for creating a database. 

Example
CREATE DATABASE College;

Database can also be created using CREATE SCHEMA

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 9 of Resources Pvt. Ltd.
Programming in Java
Creating a table in the database

Tables can be created using CREATE TABLE statement with the


following syntax.

CREATE TABLE IF NOT EXISTS `Students`.` `roll_no`


VARCHAR(15),
`full_name` VARCHAR(150) NOT NULL ,
`gender` VARCHAR(6) ,
`date_of_birth` DATE ,
`physical_address` VARCHAR(255) ,
`postal_address` VARCHAR(255) ,
`contact_number` VARCHAR(75) ,
`email` VARCHAR(255) ,
‘department’ DEPARTMENT,
PRIMARY KEY (`roll_no`) );

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 10 of Resources Pvt. Ltd.
Programming in Java
Downloading JDBC Driver
JDBC Driver is a software component that enables java application to
interact with the database.

There are 4 types of JDBC drivers:

JDBC-ODBC bridge driver


Native-API driver (Uses native language and Java to establish
connectivity)
Network Protocol driver
Thin driver

Out of the four, Network protocol driver and Thin driver are widely used
as they are written fully in Java.

These drivers are provided by database software vendors e.g.

oracle.jdbc.driver.OracleDriver 
com.mysql.jdbc.Driver 

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 11 of Resources Pvt. Ltd.
Programming in Java
Register the Driver class
The forName() method of Class class is used to register the driver class.

This method is used to dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFound
Exception  

Example to register the Oracle Driver class

Class.forName("oracle.jdbc.driver.OracleDriver");  

Example to register the MySQL Driver class

Class.forName("com.mysql.jdbc.Driver"); 

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 12 of Resources Pvt. Ltd.
Programming in Java
Create Connection Object

The getConnection() method of DriverManager class is used to


establish connection with the database.

Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLExce
ption  
2) public static Connection getConnection(String url,String name,Strin
g password)  throws SQLException  

Example to establish connection with the Oracle database

Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:db_name","system","password");  

Example to establish connection with the MySQL database

Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/db_name","root","root");  

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 13 of Resources Pvt. Ltd.
Programming in Java

Create Statement Object

The createStatement() method of Connection interface is used to


create statement. The object of statement is responsible to execute
queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException 

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 14 of Resources Pvt. Ltd.
Programming in Java
Execute the Query

The executeQuery() method of Statement interface is used to execute


queries to the database. This method returns the object of ResultSet that
can be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql) throws SQLException 

Example to excute Query

ResultSet rs=stmt.executeQuery("select * from students");  
  
while(rs.next()){  
System.out.println(rs.getInt(1)+" "+rs.getString(2));  
}  

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 15 of Resources Pvt. Ltd.
Programming in Java
Close the connection

By closing connection object statement and ResultSet will be closed


automatically. The close() method of Connection interface is used to close
the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

Con.close();

Since Java 7, JDBC has ability to use try-with-resources statement to


automatically close resources of type Connection, ResultSet, and
Statement. It avoids explicit connection closing step

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 16 of Resources Pvt. Ltd.
Programming
Example in Java
to connect Oracle database
In this example, we are connecting to an Oracle database and getting data
from students table. Here, system and oracle are the username and password
of the Oracle database
 
import java.sql.*;   //step4 execute query  
class OracleCon{   ResultSet rs=stmt.executeQuery("select * 
public static void main(String args[]) from students");  
{   while(rs.next())  
try{   System.out.println(rs.getInt(1)+"  "+rs.ge
//step1 load the driver class   tString(2)+"  "+rs.getString(3));  
Class.forName("oracle.jdbc.driver.Oracle   
Driver");   //step5 close the connection object  
   con.close();  
//step2 create  the connection object     
Connection con=DriverManager.getCon }catch(Exception e)
nection(   { System.out.println(e);}  
"jdbc:oracle:thin:@localhost:1521:xe","sy   
stem","oracle");   }  
   }  
//step3 create the statement object  
Statement stmt=con.createStatement();  
   SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 17 of Resources Pvt. Ltd.
Programming
Example in Java
to connect Oracle database
To connect java application with the Oracle database ojdbc14.jar file is required
to be loaded.

ojdbc.jar is a JDBC driver from Oracle that provides database connectivity to


Oracle Database server through the standard JDBC application program
interfaces (APIs) available in Java. Latest jar file can be downloaded from
Oracle.com

Two ways to load the jar file:


1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath in command line i.e. C:>set classpath=c:\folder\ojdbc14.jar;  

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 18 of Resources Pvt. Ltd.
Programming
Example in Java
to connect MySQL database
In this example, we are connecting to an Oracle database and getting data
from students table. Here, root and root are the username and password of
the MySQL database
 
import java.sql.*;   while(rs.next())  
class MysqlCon{   System.out.println(rs.getInt(1)+"  "+rs.ge
public static void main(String args[]) tString(2)+"  "+rs.getString(3));  
{   con.close();  
try{   }
Class.forName("com.mysql.jdbc.Driver") catch(Exception e)
;   { System.out.println(e);}  
Connection con=DriverManager.getCon }  
nection(   }  
"jdbc:mysql://localhost:3306/
sys","root","root");  
//
here sonoo is database name, root is user
name and password
  
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select 
* from emp");  
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 19 of Resources Pvt. Ltd.
Programming
Example in Java
to connect MySQL database
To connect java application with the mysql database, mysqlconnector.jar file
is required to be loaded.

MySQL provides standards-based drivers for JDBC, ODBC, and .Net enabling
developers to build database applications in their language of choice. In addition,
a native C library allows developers to embed MySQL directly into their
applications.

Two ways to load the jar file:


1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath using C:>set classpath=c:\folder\mysql-connector-java-5.0.8-
bin.jar; 

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 20 of Resources Pvt. Ltd.
Programming
Statement in Java
interfaces
To interact with database, we must use various type of commands in JDBC.

The JDBC Statement,


CallableStatement and
PreparedStatement

These interfaces define the methods and properties needed to send SQL or
PL/SQL commands and receive data from the database.

They also define methods that help bridge data type differences between Java
and SQL data types used in a database.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 21 of Resources Pvt. Ltd.
Programming
Statement in Java
interfaces

Interfaces Recommended Use


Statement Use this for general-purpose access to your database. Useful
when you are using static SQL statements at runtime. The
Statement interface cannot accept parameters.
PreparedStatement Use this when you plan to use the SQL statements many
times. The PreparedStatement interface accepts input
parameters at runtime.
CallableStatement Use this when you want to access the database stored
procedures. The CallableStatement interface can also accept
runtime input parameters

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 22 of Resources Pvt. Ltd.
Programming
Creating in Java
Statement Object
Once a connection is obtained we can interact with the database.
The JDBC Statement is used only to perform static operations without any
parameters, this can be useful only for select statement without parameters.

In order to perform interfaces define the methods and properties that enables to
send SQL or PL/SQL commands and receive data from the database like
DDL or DML queries PreparedStatement and CallableStatement objects are
used

They also define methods that help bridge data type differences between Java
and SQL data types used in a database.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 23 of Resources Pvt. Ltd.
Programming
Creating in Java
Prepared Statement Object
The DML operations like INSERT,DELETE and UPDATE— which are used to to
write operations are done using prepareStatement() method of the Connection
object created above. A call to this method takes variable bind parameters as
input parameters and creates an object instance of the PreparedStatement class.

The following line of code illustrates this:

String sql = "INSERT INTO emp VALUES (?,?,?,?,?,?,?,?)";

PreparedStatement dml_stmt = conn.prepareStatement(sql);

The input parameters are bound to this object instance using


the setXXX() methods on the PreparedStatement object. For each input bind
parameter, a setXXX() method is called. Here XXX stands for Int, String, and so
on.

dml_stmt.setInt(1, val);

Here 1 denotes that the first bind parameter is being set and val denotes an
integer variable holding a value.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 24 of Resources Pvt. Ltd.
Programming
Creating in Java
Prepared Statement Object
Once a PreparedStatement object has been constructed, the next step is to
execute the associated INSERT or UPDATE statement. This is done by using
the executeUpdate() method of the PreparedStatement object. The following line
of code illustrates this using the dml_stmt object created above:

dml_stmt.executeUpdate();

The differences between Statement object and PreparedStatement object are the


following:

A Statement object cannot accept bind parameters, whereas


a PreparedStatement object can.

A PreparedStatement precompiles the SQL and hence the precompiled SQL


statement can be reused. In this way, it optimizes the database calls.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 25 of Resources Pvt. Ltd.
Programming
Creating in Java
Prepared Statement Object
Sample code snippet

//Creating PreparedStatement object


  
PreparedStatement pstmt = con.prepareStatement("update STUDENT set
NAME = ? where ID = ?");
  
//Setting values to place holders using setter methods of PreparedStatement
object
  
pstmt.setString(1, "MyName");   //Assigns "MyName" to first place holder
          
pstmt.setInt(2, 111);     //Assigns "111" to second place holder
 
//Executing PreparedStatement
 
pstmt.executeUpdate();

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 26 of Resources Pvt. Ltd.
Programming
Creating in Statement
Callable Java Object
Callable Statements
Callable statements are used for calling Oracle/MySQL stored procedures from
Java application.

Callable statements extends prepared statements.

One can pass 3 types of parameters to stored procedures

IN – used to pass the values to stored procedure, 


OUT – used to hold the result returned by the stored procedure
IN OUT – acts as both IN and OUT parameter. 

Before calling the stored procedure, you must register OUT parameters


using registerOutParameter() method of CallableStatement.

The performance of this interface is higher than the other two interfaces.


Because, it calls the stored procedures which are already compiled and stored in
the database server.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 27 of Resources Pvt. Ltd.
Programming
Creating in Statement
Callable Java Object

//Creating CallableStatement object


 
CallableStatement cstmt = con.prepareCall("{call anyProcedure(?, ?, ?)}");
 
//Use cstmt.setter() methods to pass IN parameters
 
//Use cstmt.registerOutParameter() method to register OUT parameters
 
//Executing the CallableStatement
 
cstmt.execute();
 
//Use cstmt.getter() methods to retrieve the result returned by the stored
procedure

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 28 of Resources Pvt. Ltd.
Programming
Result Sets in Java

The SQL statements that read data from a database query, return the data in a
result set. The SELECT statement is the standard way to select rows from a
database and view them in a result set.
The java.sql.ResultSet interface represents the result set of a database query.

A ResultSet object maintains a cursor that points to the current row in the result
set. The term "result set" refers to the row and column data contained in a
ResultSet object.

The methods of the ResultSet interface can be broken down into three categories
Navigational methods: Used to move the cursor around.
Get methods: Used to view the data in the columns of the current row being
pointed by the cursor.
Update methods: Used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 29 of Resources Pvt. Ltd.
Programming
Result Sets in Java

The cursor is movable based on the properties of the ResultSet. These properties
are designated when the corresponding Statement that generates the ResultSet is
created.

JDBC provides the following connection methods to create statements with


desired ResultSet −

createStatement(int RSType, int RSConcurrency);


prepareStatement(String SQL, int RSType, int RSConcurrency);
prepareCall(String sql, int RSType, int RSConcurrency);

The first argument indicates the type of a ResultSet object and the second
argument is one of two ResultSet constants for specifying whether a result set is
read-only or updatable.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 30 of Resources Pvt. Ltd.
Programming
Result Sets in Java
Navigating a Result Set
There are several methods in the ResultSet interface that involve moving the
cursor, including −
S.N. Methods & Description
1 public void beforeFirst() throws SQLExceptionMoves the cursor just before the first row.

2 public void afterLast() throws SQLExceptionMoves the cursor just after the last row.

3 public boolean first() throws SQLExceptionMoves the cursor to the first row.

4 public void last() throws SQLExceptionMoves the cursor to the last row.

5 public boolean absolute(int row) throws SQLExceptionMoves the cursor to the specified row.

6 public boolean relative(int row) throws SQLExceptionMoves the cursor the given number of rows forward or backward,
from where it is currently pointing.

7 public boolean previous() throws SQLExceptionMoves the cursor to the previous row. This method returns false if the
previous row is off the result set.

8 public boolean next() throws SQLExceptionMoves the cursor to the next row. This method returns false if there are no more
rows in the result set.

9 public int getRow() throws SQLExceptionReturns the row number that the cursor is pointing to.

10 public void moveToInsertRow() throws SQLExceptionMoves the cursor to a special row in the result set that can be used to
insert a new row into the database. The current cursor location is remembered.

11 public void moveToCurrentRow() throws SQLExceptionMoves the cursor back to the current row if the cursor is currently
at the insert row; otherwise, this method does nothing

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 31 of Resources Pvt. Ltd.
Programming
Result Sets in Java
Viewing a Result Set
The ResultSet interface contains dozens of methods for getting the data of the
current row.

There is a get method for each of the possible data types, and each get method
has two versions −

One that takes in a column name.


One that takes in a column index.

For example, if the column you are interested in viewing contains an int, you
need to use one of the getInt() methods of ResultSet −

S.N. Methods & Description

1 public int getInt(String columnName) throws SQLExceptionReturns the int in


the current row in the column named columnName.

2 public int getInt(int columnIndex) throws SQLExceptionReturns the int in the


current row in the specified column index. The column index starts at 1, meaning the first
column of a row is 1, the second column of a row is 2, and so on.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 32 of Resources Pvt. Ltd.
Programming
Result Sets in Java
Updating a Result Set

The ResultSet interface contains a collection of update methods for updating the
data of a result set.

As with the get methods, there are two update methods for each data type −
One that takes in a column name.
One that takes in a column index.

For example, to update a String column of the current row of a result set, you
would use one of the following updateString() methods −

S.N. Methods & Description


1 public void updateString(int columnIndex, String s) throws
SQLExceptionChanges the String in the specified column to the value of s.
2 public void updateString(String columnName, String s) throws
SQLExceptionSimilar to the previous method, except that the column is
specified by its name instead of its index.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 33 of Resources Pvt. Ltd.
Programming
Result in Java
Set Metadata
Java ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the
data.

If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides
methods to get metadata from the ResultSet object.

Commonly used methods of ResultSetMetaData interface

Method Description

public int getColumnCount()throws it returns the total number of columns in


SQLException the ResultSet object.

public String getColumnName(int it returns the column name of the specified


index)throws SQLException column index.

public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.

public String getTableName(int it returns the table name for the specified
index)throws SQLException column index.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 34 of Resources Pvt. Ltd.
Programming in Java
DataBaseMetadata
Java DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database
such as database product name, database product version, driver name, name of
total number of tables, name of total number of views etc.

Commonly used methods of DatabaseMetaData interface


public String getDriverName()throws SQLException: it returns the
name of the JDBC driver.
public String getDriverVersion()throws SQLException: it returns the
version number of the JDBC driver.
public String getUserName()throws SQLException: it returns the
username of the database.
public String getDatabaseProductName()throws SQLException: it
returns the product name of the database.
public String getDatabaseProductVersion()throws SQLException: it
returns the product version of the database.
public ResultSet getTables(String catalog, String schemaPattern,
String tableNamePattern, String[] types)throws SQLException: it
returns the description of the tables of the specified catalog. The table type can
be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 35 of Resources Pvt. Ltd.
Programming
BLOB inObjects
and CLOB Java
In the JDBC API, 
java.sql.Blob is the mapping for the SQL BLOB (binary large object)
type; 
java.sql.Clob is the mapping for the SQL CLOB (character large object)
type.

BLOB and CLOB objects are collectively referred to as LOBs (large objects).

To use the java.sql.Blob and java.sql.Clob features:Use the SQL BLOB type for


columns which hold very large binary values.

Use the SQL CLOB type for columns which hold very large string values.

Use the getBlob and getClob methods of the java.sql.ResultSet interface to


retrieve a LOB using its locator.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 36 of Resources Pvt. Ltd.
Programming
Storing inDatabase
image in Java
One can store images in the database in java by the help
of PreparedStatement interface.

The setBinaryStream() method of PreparedStatement is used to set Binary


information into the parameterIndex.

Signature of setBinaryStream method


The syntax of setBinaryStream() method is given below

1) public void setBinaryStream(int paramIndex,InputStream stream)  
throws SQLException  

2) public void setBinaryStream(int paramIndex,InputStream stream,long leng
th)  throws SQLException 

For storing image into the database, BLOB (Binary Large Object) datatype is
used in the table. For example:
CREATE TABLE  "IMGTABLE"   
   (    "NAME" VARCHAR2(4000),   
    "PHOTO" BLOB  
   )   
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 37 of Resources Pvt. Ltd.
Programming
Retrieving in in
image Java
Database
To retrieve image from Oracle database
By the help of PreparedStatement we can retrieve and store the image in the database.

The getBlob() method of PreparedStatement is used to get Binary information, it returns


the instance of Blob. After calling the getBytes() method on the blob object, we can get the
array of binary information that can be written into the image file.

Signature of getBlob() method of PreparedStatement


public Blob getBlob()throws SQLException  

Signature of getBytes() method of Blob interface


public  byte[] getBytes(long pos, int length)throws SQLException  

Code snippet to retrieve image

PreparedStatement ps=con.prepareStatement("select * from imgtable");  

ResultSet rs=ps.executeQuery();  
if(rs.next()){//now on 1st row  
              Blob b=rs.getBlob(2);//2 refers to data in 2nd column  
byte barr[]=b.getBytes(1,(int)b.length());//1  refers to 1st image  
              FileOutputStream fout=new FileOutputStream("d:\\sample.jpg");  

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 38 of Resources Pvt. Ltd.
Programming
Storing in Java
file in Oracle database
The setCharacterStream() method of PreparedStatement is used to set character
information into the parameterIndex.

For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:

CREATE TABLE  "FILETABLE"   
   (    "ID" NUMBER,   
    "NAME" CLOB  
   ) 

// Code snippet
PreparedStatement ps=con.prepareStatement(  
"insert into filetable values(?,?)");  
              
File f=new File("d:\\myfile.txt");  
FileReader fr=new FileReader(f);  
              
ps.setInt(1,101);  
ps.setCharacterStream(2,fr,(int)f.length());  
int i=ps.executeUpdate();  

con.close();  

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 39 of Resources Pvt. Ltd.
Programming
Retrieving in Java
file from Oracle database
The getClob() method of PreparedStatement is used to get file information from the
database.

// Code snippet
PreparedStatement ps=con.prepareStatement("select * from filetable");  
ResultSet rs=ps.executeQuery();  
rs.next();//now on 1st row  
              
Clob c=rs.getClob(2);  
Reader r=c.getCharacterStream();              
              
FileWriter fw=new FileWriter("d:\\retrivefile.txt");  
              
int i;  
while((i=r.read())!=-1)  
fw.write((char)i);  
              
fw.close();  
con.close();  

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 40 of Resources Pvt. Ltd.
Programming
Transaction in Java in JDBC
management
A database transaction is a sequence of actions that are treated as a single unit of work.
These actions should either complete entirely or take no effect at all. Transaction
management is an important part of RDBMS-oriented enterprise application to ensure
data integrity and consistency.

Transaction represents a single unit of work.


The ACID properties describes the transaction management well. ACID stands for
Atomicity, Consistency, isolation and durability.

Atomicity means either all successful or none.


Consistency ensures bringing the database from one consistent state to another
consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the
event of errors, power loss etc.

Advantage of Transaction Mangaement


fast performance It makes the performance fast because database is hit at the time of
commit.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 41 of Resources Pvt. Ltd.
Programming
Transaction in Java in JDBC
management

In JDBC, Connection interface provides methods to manage transaction.

Method Description

void setAutoCommit(boolean status) It is true bydefault means each transaction


is committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 42 of Resources Pvt. Ltd.
Programming
Batch in in
processing Java
JDBC
Instead of executing a single query, we can execute a batch (group) of queries. It makes the
performance fast.

The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for


batch processing.

Advantage of Batch Processing


Fast Performance

Methods of Statement interface


The required methods for batch processing are given below:

Method Description

void addBatch(String query) It adds query into batch.

int[] executeBatch() It executes the batch of queries.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 43 of Resources Pvt. Ltd.
Programming
New in Java
features added in JDBC4.0
• Auto loading of JDBC driver class
• Connection management enhancements
• Support for ROWID in SQL. ROWID is a pseudocolumn
that defines a single row in a table
• Exception handling
• A new interface for SQLXML is added which is a mapping
for theXML data type in SQL

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 44 of Resources Pvt. Ltd.
Programming in Java
MCQs

1. RDBMS supports ACID property. Here ACID stands for

a.Autonomous, Complex, Independent and durability


b.Atomicity, Consistency, Isolation and Durability
c.Autonomous, Complete, Independent and Desirable
d.Atomocity, Complete, Isolation and Disrable

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 45 of Resources Pvt. Ltd.
Programming in Java

Answer:
b) Atomicity, Consistency, Isolation and Durability

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 46 of Resources Pvt. Ltd.
Programming in Java
MCQs

2.Which packages contains JDBC classes


a.java.jdbc and java.sql
b.java.jdbc and javax.jdbc
c.java.sql and javax.sql
d.java.rdb and javax.rdb

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 47 of Resources Pvt. Ltd.
Programming in Java

Answer:
c) java.sql and javax.sql

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 48 of Resources Pvt. Ltd.
Programming in Java
MCQs

3. Which interface gives details about the table


a.ResultSet
b.ResultSetMetaData
c.Statement
d.PreparedStatement

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 49 of Resources Pvt. Ltd.
Programming in Java

Answer:
b)ResultSetMetaData

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 50 of Resources Pvt. Ltd.
Programming in Java
MCQs

4. Which interface is used to store and retrieve images


a.Statements
b.CallableStatements
c.PreparedStatements
d.Connections

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 51 of Resources Pvt. Ltd.
Programming in Java

Answer:
c)PreparedStatements

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 52 of Resources Pvt. Ltd.
Programming in Java
MCQs

5. Absolute method in ResultSet performs


a.Moves the cursor to a row which matches with the value passed
b.Moves the cursor to a row to the record of given index
c.Returns the value of a given attribute
d.Returns size of the given table

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 53 of Resources Pvt. Ltd.
Programming in Java

Answer:
b) Moves the cursor to a row to the record of given index

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 54 of Resources Pvt. Ltd.
Programming in Java
MCQs

6. Which of the following is used to call stored procedures


a.Statements
b.PreparedStatements
c.CallableStatements
d.CallingProcedure

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 55 of Resources Pvt. Ltd.
Programming in Java

Answer:
c) CallableStatements

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 56 of Resources Pvt. Ltd.
Programming in Java
MCQs

7. Which objects is/are used to do DDL or DML operations


a.Statements
b.PreparedStatements
c.CallableStatements
d.Both b and C

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 57 of Resources Pvt. Ltd.
Programming in Java

Answer:
d) Both b and C
PreparedStatements &CallableStatements

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 58 of Resources Pvt. Ltd.
Programming in Java
MCQs

8. Which method is used to perform DML in JDBC


a.executeQuery
b.executeUpdate
c.execute
d.executeResult

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 59 of Resources Pvt. Ltd.
Programming in Java

Answer:
b) executeUpdate

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 60 of Resources Pvt. Ltd.
Programming in Java
MCQs

9.How do you get to know the warnings that are generated by SQL in your application
a.You must catch the checked SQLException which is thrown by the method that executes
the Statement
b.You must catch the unchecked SQLException which is thrown by the method that
executes the Statement
c.You must invoke the getWarnings method on the Statement object
d.You must query the ResultSet about the warnings.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 61 of Resources Pvt. Ltd.
Programming in Java

Answer:
c) You must invoke the getWarnings method on the Statement object

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 62 of Resources Pvt. Ltd.
Programming in Java
MCQs

10. What statements are correct about JDBC transactions?


a. A transaction is a set of successfully executed statements in the database
b. A transaction is finished when commit() or rollback() is called on the Connection object,
c. A transaction is finished when commit() or rollback() is called on the Transaction object
d. A transaction is finished when close() is called on the Connection object

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 63 of Resources Pvt. Ltd.
Programming in Java

Answer:
d) A transaction is finished when close() is called on the Connection
object

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 64 of Resources Pvt. Ltd.
Programming in Java
MCQs

11. Advantage of transaction management is


a.Fast because it stores only right amount of data
b.Fast because it accesses the database only during store
c.Fast because it accesses the database only during commit
d.Effective in terms of memory management

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 65 of Resources Pvt. Ltd.
Programming in Java

Answer:
c) Fast because it accesses the database only during commit Fast
because it accesses the database only during commit

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 66 of Resources Pvt. Ltd.
Programming in Java
MCQs

12. What happens if you call the method close() on a ResultSet object?
a. the method close() does not exist for a ResultSet. Only Connections can be closed.
b. the database and JDBC resources are released
c. you will get a SQLException, because only Statement objects can close ResultSets
d. the ResultSet, together with the Statement which created it and the Connection from
which the Statement was retrieved, will be closed and release all database and JDBC
resources

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 67 of Resources Pvt. Ltd.
Programming in Java

Answer:
b) the database and JDBC resources are released

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 68 of Resources Pvt. Ltd.
Programming in Java
MCQs

13. Which is the best way to store an attribute of large String value in SQL
a.SQL CLOB
b.SQL BLOB
c.SQL SLOB
d.SQL FLOB

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 69 of Resources Pvt. Ltd.
Programming in Java

Answer:
a) SQL CLOB

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 70 of Resources Pvt. Ltd.
Programming in Java
MCQs

14. ROWID in SQL is


a.Primary key
b.Candiate key
c.Pseudo column that uniquely identifies a single row
d.Foreign key

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 71 of Resources Pvt. Ltd.
Programming in Java

Answer:
c)Pseudo column that uniquely identifies a single row

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 72 of Resources Pvt. Ltd.
Programming in Java
MCQs

15. To execute a series of SQL commands we use


a.addBatch
b.runBatch
c.executeBatch
d.executeUpdate

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 73 of Resources Pvt. Ltd.
Programming in Java

Answer:
c) executeBatch

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 74 of Resources Pvt. Ltd.
Programming in Java
Thank You!!!!

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 75 of Resources Pvt. Ltd.

You might also like