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

Chapter5 DB

Uploaded by

Rohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Chapter5 DB

Uploaded by

Rohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Chapter-5

Interacting with Database

Marks=12

Prepared by: Prof. Biradar R.Y.


Introduction to JDBC
• JDBC - Java Database Connectivity
• JDBC is a Java API to connect and execute the query
with the database
• Used to access tabular data stored in any relational
database
• Package: java.sql , javax.sql
• JDBC helps to write Java applications that manage
these three programming activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the
database in answer to your query
Introduction to JDBC (Cont..)
• A driver works as an interface between the
client and a database server.

• Allow a java application to send request made


by user to any specific DBMS.
• JDBC supports a wide level of portability.
• JDBC provides interfaces that are compatible
with java application
JDBC API
• JDBC is a Java API that is used to connect
and execute query for the database.
• JDBC API uses jdbc drivers to connects to
the database.
• Using JDBC API, we can save, update,
delete and fetch data from the database
Classes in JDBC API
1. DriverManager class
2. Type class
3. Date class
Interfaces in JDBC API
1. Driver interface
2. Connection interface
3. Statement interface
4. PreparedStatement interface
5. CallableStatement interface
6. ResultSet interface
7. ResultSetMetaData interface
8. DatabaseMetaData interface
9. Blob interface ( Binary Large Object)
10.Clob interface ( Character Large Object)
Why JDBC?

• JDBC drivers written in Java language.


• Supports portability
• So platform independent and secured
• JDBC is object oriented.
ODBC
• Open Data Base Connectivity
• Developed by Microsoft for the Windows
platform as the way for Windows applications
to access Microsoft databases (SQL Server,
FoxPro, MS Access)
• developed in C programming.
• It is low level, high performance interface that
is designed specially for relational data stores.
ODBC
• We can use ODBC for any language like C,C+
+,Java etc.
• ODBC is procedural
• ODBC permits maximum interoperability,
which means a single application can access
different DBMS.
• ODBC handles the SQL request and converts it
into a request the individual database system
understands
JDBC Architecture
• The JDBC API supports both two-tier & three-tier
architecture
• Two-tier Architecture for Data Access:
– client/server configuration
– divided into two parts: 1) Client Application (Client Tier)
2) Database (Data Tier)
Two-tier Architecture for Data Access:

• Advantages:
1. Easy to maintain
2. Communication is faster.
• Disadvantages:
1. performance will be degrade upon
increasing the users.
• Three-tier Architecture for Data Access:
– divided into three parts: 1)Client layer
2)Business layer
3)Data layer
Three-tier Architecture for Data Access:

• Advantages:
1. Scalability
2. Performance
3. Better Re-usability.
4. Improve Data Integrity.
5. Improved Security – Client can’t directly access
the database.
6. Easy to maintain, to manage, to scale, loosely
coupled etc.
• Disadvantages:
1. Increased Complexity
Java
Application

JDBC
API

Data Base Drivers

Access SQL DB2 Informix MySQ L Sybase


Server
JDBC Drivers and its types
• a software component that enables java application
to interact with the database
• JDBC drivers are client-side adapters that convert
requests from Java programs to a protocol that the
DBMS can understand
• four categories of drivers
1) Type 1 Driver : JDBC-ODBC Bridge.
2) Type 2 Driver : Native-API Driver (Partly Java driver).
3) Type 3 Driver : Network-Protocol Driver (Pure Java
driver for database Middleware).
4) Type 4 Driver : Pure Java Driver, Thin Driver,100% Java
Type 1 Driver : JDBC-ODBC Bridge
• Also known as a JDBC-ODBC Bridge.
• This driver uses ODBC driver to connect to the
database.
• It converts JDBC methods into ODBC function calls.
• also called Universal driver because it can be used to
connect to any of the databases.
• Sun provides a JDBC-ODBC Bridge driver by
“sun.jdbc.odbc.JdbcOdbcDriver”.
• The ODBC Driver needs to be installed on the client
machine.
• In Java 8, the JDBC-ODBC Bridge has been removed.
Type 1 Driver : JDBC-ODBC Bridge
• Advantage of bridge driver
– Easy to use
– It is a database independent driver. it can be used to
connect to any of the databases.
– Can be easily connected to any database.

• Disadvantage of bridge driver


– It is a slow driver so not used in real time application
– Because of Odbc connectivity it is a platform dependent
driver.
– It is not a portable driver.
– It is not suitable for applet to connect with database.
Type 2 Driver: Native-API Driver (Partly Java driver) :

• It uses the client side libraries of the database


• This driver converts the JDBC method calls
into native(C/C++) calls of the database API.
• Also known as a Native-API driver.
• Data transferred through this driver is more
secure
• cannot be used in the web-based application.
• This driver supports all JAVA applications
except applets.
Type 2 Driver: Native-API Driver (Partly Java driver) :

• Advantages:
– faster than a type 1 driver
• Disadvantages:
– This driver is a platform dependent.
– Native API driver is database dependent
– It is not a portable driver
– Driver needs to be installed separately in
individual client machines
– client library needs to be installed on client
machine.
Type 3 Driver: Network-Protocol Driver (Pure Java driver for
database Middleware) :

• uses the middle tier.


• middle tier converts JDBC method calls into
the vendor specific database protocol
• The same driver can be used for multiple
databases.
• It’s also known as a Network-Protocol driver as
well as a JAVA driver for database middleware.
• used in any web application as well as on
internet
Type 3 Driver: Network-Protocol Driver (Pure Java driver for
database Middleware) :

• Advantage of Network Protocol driver


– No client side library is required because of application
server
– This driver is both database and platform independent
driver
• Disadvantage of Network Protocol driver
– Network support is required on client machine.
– Requires database-specific coding to be done in the
middle tier.
– Maintenance becomes costly because it requires
database-specific coding to be done in the middle tier.
Type 4 Driver: Thin Driver (Pure Java driver directly connected to
database)

• It converts JDBC method calls directly into the


vendor specific database protocol
• Also known as thin driver
• It’s a 100% pure JAVA Driver so it’s a platform
independent.
• There is a separate driver needed for each
database at the client side.
Type 4 Driver: Thin Driver (Pure Java driver directly connected to
database)

• Advantage of Thin driver


– Thin driver is the fastest driver among all Jdbc
drivers.
– It is portable driver because it is platform
independent.
– It can be used to connect an applet with the
database.
• Disadvantage of Thin driver
– Thin driver is a database dependent driver.
Which Driver should be used?
• If you are accessing one type of database, such as Oracle,
Sybase, or IBM, the preferred driver type is 4.
• If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
• Type 2 drivers are useful in situations, where a type 3
or
type 4 driver is not available yet for your database.
• The type 1 driver is not considered a deployment-level
driver, and is typically used for development and testing
purposes only.
JDBC APIs:
Class or Interface Description
java.sql.Connection Create a connection with specific
database.
java.sql.DriverManager The task of DriverManager class is
to manage the database driver
java.sql.Statement It executes SQL statements for
particular connection and retrieve
the results

java.sql.PreparedStatement It allows the programmer to create


prepared SQL statements
java.sql.CallableStatement It executes stored procedures
java.sql.ResultSet This interface provides methods to
get result row by row generated by
SELECT statements
5 Steps to connect to the database in java

1. Register the driver class


2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object
MCQ
• Arrange the following sequence of steps used
to connect database 2M
1. Execute the query
2. Create the connection object
3. Close the connection object
4. Register the driver class
5. Create the Statement object

A)1,2,3,4,5 B)2,5,4,1,3 C)4,2,5,1,3 D) 3,4,2,1,5


1) 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 ClassNotFoundException
• Example:
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.mysql.jdbc.Driver");
2) Create the connection object
• 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 SQLException
• 2) public static Connection getConnection(String url,
String name,String password) throws SQLException
2) Create the connection object
• Example:
1)Connection con=DriverManager.getConnection( "jdbc:odbc:mydsn”);
2)Connection con=DriverManager.getConnection( "jdbc:odbc:mydsn
", "system","password");

3)Connection con=DriverManager.getConnection("jdbc:mysql://
localhost:3306/dbname","root",“pwd");

4)Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
3) Create the Statement object
• 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
• Example:
Statement stmt=con.createStatement();
4) Execute the query
• executeQuery() method of Statement interface is used
to execute queries to the database
• 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:
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Close the connection object

• The close() method of Connection interface is


used to close the connection.
• Syntax of close() method
public void close()throws SQLException
• Example:
con.close();
Create a ODBC connection for the
Database (Creating DSN)
1. Click Start, and then click Control Panel.
2. In the Control Panel, double-click Administrative
Tools.
• 3.In the Administrative Tools dialog box,
double-click Data Sources (ODBC).
4.The ODBC Data Source Administrator dialog
box appears.
5. Click User DSN, System DSN, or File DSN, depending
on the type of data source you want to add.
6. Click Add.
7.Select the driver that you want to use, and
then click Finish or Next.
8. Selecting the Database file and Naming it
and/or assigning name and password
The Connection interface:
• used to connect java application with
particular database
• Once connection with database is created, we
can execute SQL statements for that particular
connection using object of Connection and
retrieve the results.
• Methods
Method Description

void close() This method closes the Connection from database.

void commit() This method makes all the changes made since the
last commit or rollback permanent. It throws
SQLExeception.
Method Description
void rollback() This method undoes all changes made to
the database.
boolean isClosed() Return true if the connection is close
else return false.
void setAutoCommit(boolean It is used to set the commit status.By
status) default it is true.

Statement createStatement() creates a statement object that can be


used to execute SQL queries. It throws
SQLExeception.

Statement creates a statement object will generate


createStatement(int RSType, ResultSet objects with the given type
int RSConcurrency) and concurrency.
Method Description
CallableStatement It creates CallableStatement object for calling
prepareCall(String s) the stored procedures from database. It
throws SQLExeception.

CallableStatement creates a CallableStatement object will


prepareCall(String s, int generate ResultSet objects with the given type
RSType, int and concurrency.
RSConcurrency)

PreparedStatement It creates an PrepareStatement object for


prepareStatement(Strin sending dynamic SQL statements to the
g s) database. It throws SQLExeception.

PreparedStatement creates a PreparedStatement object will


prepareStatement(Strin generate ResultSet objects with the given type
g s, int RSType, int and concurrency.
RSConcurrency)
Statement Interface:

• Used to execute a static query


• It’s a very simple and easy so it also called as
“Simple Statement”.
Method Description
void close() It closes Statement object.
boolean execute(String s) It executes the SQL statement specified
by s.
ResultSet getResulSet() It retrieves the ResultSet that is generated
by the execute() method.
ResultSet It is used to execute the select SQL
executeQuery(String s) statement specified by s and returns the
object of type ResultSet.
int getMaxRows() Returns the maximum number of rows
those are generated by the
executeQuery() method
int executeUpdate(String s) It executes the SQL statement specified
by s. The SQL statement may be a SQL
create, insert, update and delete
statement.
PreparedStatement Interface
• used to execute a dynamic query
• Also used to execute a parameterized or
precompiled SQL statement/query
• to pass different values to an query “?” is used in
the query and the actual values can be passed
using the setXXX() method at the time of
execution.
• Query with IN parameter uses “?”.
• Syntax :
setXXX(int location ,XXX value);
Where XXX means a data type
• For example:
String query = "Select * from Data where
ID = ? and Name = ? ";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, 1);
ps.setString(2, “xyz");
Method Description
void close() It closes PreparedStatement object.
boolean execute() It executes the dynamic query in the
object of type Prepared Statement.
ResultSet getResult It retrieves the ResultSet that is generated
by the execute() method.
ResultSet executeQuery() It is used to execute dynamic query in the
object of type Prepared Statement and
returns the object of type ResultSet.
int getMaxRows() Returns the maximum number of rows
those are generated by the
executeQuery() method
int executeUpdate() It executes the execute dynamic query in
the object of type Prepared Statement.
The SQL statement may be a SQL create,
insert, update and delete statement.
CallableStatement Interface
• used to call the stored procedures and
functions
• use of stored procedures and functions gives
better performance because these are
precompiled.
• Example:

CallableStatement stmt=con.prepareCall("{call
myprocedure(?,?)}");
ResultSet interface
• Maintains a cursor pointing to a row of a
table.
• Initially, cursor points to before the first row.
• By default, ResultSet object can be moved
forward only and it is not updatable.
Type of ResultSet
ResultSet.TYPE_FORWARD_ONLY The cursor can only move
forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE It indicates that ResultSet
object that is scrollable but
generally not sensitive to
changes to the ResultSet data.
ResultSet.TYPE_SCROLL_SENSITIVE It indicates that ResultSet
object that is scrollable and
sensitive to changes to the
ResultSet data.
Concurrency of ResultSet
ResultSet.CONCUR_READ_ONL Creates a read-only result set. This
Y is the default
ResultSet.CONCUR_UPDATABLE Creates an updatable result set.
Navigating a Result Set
Method Description
public void beforeFirst() throws Moves the cursor just before
SQLException the first row.
public void afterLast() throws Moves the cursor just after the
SQLException last row.
public boolean first() throws Moves the cursor to the first
SQLException row.
public void last() throws Moves the cursor to the last
SQLException row.
public boolean absolute(int row) Moves the cursor to the
throws SQLException specified row
public boolean relative(int row) Moves the cursor the given
throws SQLException number of rows forward or
backward, from where it is
currently pointing
Method Description
public boolean previous() throws Moves the cursor to the
SQLException previous row
public boolean next() throws Moves the cursor to the next
SQLException row. This method returns false
if there are no more rows in
the result set.
public int getRow() throws Returns the row number that
SQLException the cursor is pointing to.
Viewing a ResultSet
• 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.

int getXXX(String columnName) throws SQLException

int getXXX(int columnIndex) throws SQLException

XXX means a data type


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