Chapter 3 - JDBC

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 37

1

2
 Programs connect to, and interact with, relational databases via an interface—

software that facilitates communications between a database management


system and a program.
 Java programs communicate with databases and manipulate their data using

the JDBC API.


 A JDBC driver enables Java applications to connect to a database in a

particular DBMS and allows you to retrieve and manipulate database data.
 Package java.sql contains classes and interfaces for accessing relational

databases in Java.
 Using the JDBC API enables developers to change the underlying DBMS

without modifying the Java code that accesses the database.


 The JDBC API can also be used to interact with multiple data sources in a
3 distributed, heterogeneous environment.
Fig 4.1: JDBC

4
The JDBC architecture is sometimes classified

as: two-tier and three-tier.


Figure 3.2. (i) and (ii) show the JDBC two-tier

and three-tier architectures.

5
Fig 4.2. JDBC Architecture (i) Two-tier (ii) Three-tier
6
Java provides an API for accessing and
processing data stored in a data source.
Table 1: Java JDBC classes and
interfaces

7
Steps to connect to the database in java

There are 5 steps to connect any java application with the


database in java using JDBC. They are as follows:

1.Register the driver class

2.Creating a connection

3.Creating statement

4.Executing queries

5.Closing a connection

8
Steps to connect to the database in java

1) Register the driver class


oThe 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 ClassNotFoundException

Example to register the Mysql /Oracle Driver class

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

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

9
2) Create the connection object

oThe getConnection() method of DriverManager class is used to establish

connection with the database.


Syntax of getConnection() method

Example to establish connection with the MySQL database


Connection con=DriverManager.getConnection("jdbc:mysql://hostname:port/dbname",“un",“PW");

//here dbname is a database name, un is a username and PW is a password

10
3) Create the Statement object
oThe createStatement() method of Connection interface is used to create

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


database.

oSyntax of createStatement() method

public Statement createStatement()throws SQLException

Example: Statement stmt=con.createStatement();

11
4) Execute the query
oThe 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 execute query


ResultSet rs=stmt.executeQuery("select * from stud");

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
12
5) Close the connection object
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 : con.close();

JDBC example

13
o DriverManager class

The DriverManager class acts as an interface between user and drivers. It


keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
o Commonly used methods of DriverManager class:

public static Connection getConnection(String url);

public static Connection getConnection(String url,String


userName,String password);
14
o Connection interface

A Connection is the session between java application and database. The

Connection interface is a factory of Statement, PreparedStatement, and

DatabaseMetaData i.e. object of Connection can be used to get the object

of Statement and DatabaseMetaData. The Connection interface provide

many methods for transaction management like commit(),rollback() etc.

By default, connection commits the changes after executing queries.

15
o Connection interface

Commonly used methods of Connection interface:

1) public Statement createStatement(): creates a statement


object that can be used to execute SQL queries.

2) public Statement createStatement(int resultSetType,int


resultSetConcurrency): Creates a Statement object that will

generate ResultSet objects with the given type and


concurrency.

16
3) public void setAutoCommit(boolean status): is used to set the
commit status. By default it is true.

4) public void commit(): saves the changes made since the previous
commit/rollback permanent.

5) public void rollback(): Drops all changes made since the previous
commit/rollback.

6) public void close(): closes the connection and Releases a JDBC


resources immediately.

17
o 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.

methods of Statement interface


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
18
o ResultSet interface

The object of ResultSet maintains a cursor pointing to a particular row of data.


Initially, cursor points to before the first row.

By default, ResultSet object can be moved forward only and it is not


updatable.

But we can make this object to move forward and backward direction by
passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as
updatable by:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE


,
ResultSet.CONCUR_UPDATABLE);
Example

19
o ResultSet interface

ResultSet static
Description
type constant
TYPE_FORWARD_ONLY Specifies that a ResultSet’s cursor can move only in the forward
direction (i.e., from the first row to the last row in the ResultSet).
TYPE_SCROLL_INSENSITIVE Specifies that a ResultSet’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet
processing are not reflected in the ResultSet unless the program
queries the database again.
TYPE_SCROLL_SENSITIVE Specifies that a ResultSet’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet
processing are reflected immediately in the ResultSet.

ResultSet constants for specifying ResultSet type.

20
o ResultSet interface

ResultSet static
Description
concurrency constant
CONCUR_READ_ONLY Specifies that a ResultSet cannot be updated (i.e., changes to the ResultSet
contents cannot be reflected in the database with ResultSet’s update methods).
CONCUR_UPDATABLE Specifies that a ResultSet can be updated (i.e., changes to the ResultSet
contents can be reflected in the database with ResultSet’s update methods).

ResultSet constants for specifying result properties

21
o PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It


is used to execute parameterized query.

Example: 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.

Example1

22
o 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.

The getMetaData() method of ResultSet interface returns the object of


ResultSetMetaData.

Syntax: public ResultSetMetaData getMetaData()throws SQLException

23
o ResultSetMetaData Interface
Method Description
public int it returns the total number of
getColumnCount()throws columns in the ResultSet
SQLException object.
public String
it returns the column name of
getColumnName(int
the specified column index.
index)throws SQLException
public String
it returns the column type
getColumnTypeName(int
name for the specified index.
index)throws SQLException
public String getTableName(int it returns the table name for
index)throws SQLException the specified column index.

Example1 Example2
24
o 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.

The getMetaData() method of Connection interface returns the object of


DatabaseMetaData.

Syntax: public DatabaseMetaData getMetaData()throws SQLException

25
o 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.

26
Example
o CallableStatement Interface

To call the stored procedures and functions, CallableStatement


interface is used. 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

27
 How to get the instance of CallableStatement?

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


CallableStatement.

Syntax:

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


The example to get the instance of CallableStatement is given below:
o CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

o It calls the procedure myprocedure that receives 2 arguments.

28
 Example of CallableStatement

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 "INSERTrecord"


(id IN VARCHAR, Name VARCHAR,Gender IN
VARCHAR,Department IN
VARCHAR)
is
begin
insert into stud values(id,Name,Gender,Department);
end;
29
o 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.

30
o Advantage of Transaction Management

fast performance : it makes the performance fast because


database is hit at the time of commit.

31
o In JDBC, Connection interface provides methods to

manage transaction.
Method Description
void It is true bydefault means
setAutoCommit(boolean each transaction is
status) committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.

Example

32
o Batch Processing in 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
o Advantage: Fast Performance

Methods of Statement interface


Method Description
void addBatch(String
It adds query into batch.
query)
It executes the batch of
int[] executeBatch()
queries.
33
Let's see the simple example of batch processing in jdbc.

It follows following steps:

1.Load the driver class

2.Create Connection

3.Create Statement

4.Add query in the batch

5.Execute Batch

6.Close Connection

Example

34
o JDBC RowSet

The instance of RowSet is the java bean component because it has properties
and java bean notification mechanism. It is the wrapper of ResultSet. It
holds tabular data like ResultSet but it is easy and flexible to use.

The implementation classes of RowSet interface are as follows:


 JdbcRowSet

 CachedRowSet

 WebRowSet

 JoinRowSet

 FilteredRowSet
35
o Steps to create and execute RowSet.

JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();


rowSet.setUrl("jdbc:mysql://localhost:3306/student","root","root");
rowSet.setUsername(“root");
rowSet.setPassword(“root");

rowSet.setCommand("select * from stud");


rowSet.execute();

o Advantage of RowSet
 It is easy and flexible to use
 It is Scrollable and Updatable by default

Example

36
37

You might also like