0% found this document useful (0 votes)
170 views60 pages

Java Database Connectivity (JDBC)

The document discusses Java Database Connectivity (JDBC) which is an API for connecting Java programs to databases. It provides an overview of the JDBC process including: 1) Loading the appropriate JDBC driver for the target database. 2) Creating a connection to the database using the DriverManager and a connection URL string specifying details like the database host name/IP and port. 3) Creating statement objects like Statement, PreparedStatement, CallableStatement to execute SQL queries and updates on the database connection. 4) Processing the results by iterating through the ResultSet object returned by executed queries. The different types of JDBC drivers - from Type 1 Bridge drivers to native and

Uploaded by

Thanmayee Thanu
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)
170 views60 pages

Java Database Connectivity (JDBC)

The document discusses Java Database Connectivity (JDBC) which is an API for connecting Java programs to databases. It provides an overview of the JDBC process including: 1) Loading the appropriate JDBC driver for the target database. 2) Creating a connection to the database using the DriverManager and a connection URL string specifying details like the database host name/IP and port. 3) Creating statement objects like Statement, PreparedStatement, CallableStatement to execute SQL queries and updates on the database connection. 4) Processing the results by iterating through the ResultSet object returned by executed queries. The different types of JDBC drivers - from Type 1 Bridge drivers to native and

Uploaded by

Thanmayee Thanu
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/ 60

Java Database Connectivity

(JDBC)
Contents
• Data Base
• Database Schema
• A Brief Overview Of The JDBC Process
• JDBC Driver Types
• JDBC Packages
• Database Connection
• Creating, Inserting, Updating And Deleting Data In Database
Tables
• Result Set
Data Base & Database Schema
• Database is a large collection of related data that can be stored
generally describes activities of an organization.
• A database management system (DBMS) is a collection of
programs (software) for defining, creating, manipulating and
maintaining a database.
• Database Schema refers to the overall structure of a database.
• The description of a database is called the database schema,
which is specified during database design and is not expected to
change frequently
Cont …

STUDENT

Name Snumber Class Major

• TEACHER

TeacherName TeacherId TeacherDepartment TeachingcourseId


Java Database Connectivity (JDBC)
• Java API for Database Connectivity
• JDBC is an application program interface (API) specification for
connecting programs written in Java to the data in popular databases
• JDBC is a java API to connect and execute query with the database
• JDBC is used for accessing databases from Java applications
• JDBC was developed by Sun Microsystems and JavaSoft
Database Connectivity History
Before APIs like JDBC and ODBC, database connectivity was tedious:

> Database vendor provided function libraries for database access.

> Connectivity library was proprietary.

> Data access portions had to be rewritten with changes in the application.

> Application developers were stuck with a particular database product for a given
application
ODBC(Open Database Connectivity)

> A standard or open application programming interface (API) for accessing a database

> Developed by SQL Access Group, chiefly Microsoft, in 1992

> Access to various kinds of Databases

> Allows programs to use SQL requests that will access databases without knowledge of
the proprietary interfaces to the databases
ODBC Requirements
 An ODBC software for a particular OS.
 A separate module or driver for each database to be accessed
 ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured).
 That is why Java has defined its own API (JDBC API) that uses JDBC
drivers (written in Java language).
Why Java ???
> Write once, run anywhere

> Object-relational mapping


> databases optimized for searching/indexing
> objects optimized for engineering/flexibility

> Network independence


> Works across Internet Protocol

> Database independence


> Java can access any database vendor

> Ease of administration


JDBC Architecture
JDBC Architecture
JDBC API –
• The JDBC API defines the Java interfaces and classes that programmers used to connect
to databases and send queries.
• Some of the important JDBC API classes or interfaces are DriverManager ,Connection
,Statement, PreparedStatement,CallableStatement, ResultSet 
JDBC Driver Manager –
• It is class that loads database specific drivers in to an application to establish
connection with database.
• The DriverManager 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.
JDBC Architecture
• JDBC Driver is a software component that enables java application to interact
with the database
• JDBC driver is a small piece of software that allows JDBC to connect to different
databases.
• JDBC driver converts JDBC calls to database specific calls.
Essentially, a JDBC driver makes it possible to do three things:
• Establish a connection with a data source.
• Send queries and update statements to the data source.
• Process the results
JDBC Drivers Types
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 : Native-Protocol Driver(Pure Java driver directly connected
to database).
Type 1 Driver : JDBC-ODBC Bridge driver
Type 1 Driver : JDBC-ODBC Bridge driver
• The type 1 driver which is also known as a JDBC-ODBC Bridge  driver.
• The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
• The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC
function calls passed to the ODBC driver
• ODBC driver converts ODBC calls to database specific calls.
• Sun provides a JDBC-ODBC Bridge driver by
“sun.jdbc.odbc.JdbcOdbcDriver”.
• The driver is a platform dependent because it uses ODBC which is depends
on native libraries of the operating system.
• for example, ODBC must be installed on the computer and the database
must support ODBC driver
Cont ..
• Type 1 is the simplest compare to all other driver but it’s a platform specific i.e. only on
Microsoft platform.
• The JDBC-ODBC Bridge is used only when there is no PURE-JAVA driver available for a
particular database
Advantages:
•easy to use.
•can be easily connected to any database.
Disadvantages:
•Performance degraded because JDBC method call is converted into the ODBC function
calls.
•The ODBC driver needs to be installed on the client machine.
Type 2 Driver : Native-API Driver (Partly Java driver).
Type 2 Driver : Native-API Driver (Partly Java driver).

• The JDBC type 2 driver uses the libraries of the database which is available
at client side 
• The driver converts JDBC method calls into native calls of the database API
• so this driver is also known as a Native-API driver
• These drivers are typically provided by the database vendors.
• The vendor-specific driver must be installed on each client machine.
• If we change the Database, we have to change the native API, as it is
specific to a database
Type 2 Driver : Native-API Driver (Partly Java driver).

Advantage:
•performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
•The Native driver needs to be installed on the each client machine.
•The Vendor client library needs to be installed on client machine.
Type 3 Driver : Network-Protocol Driver(Pure Java driver for database
Middleware).
Cont…

•The Network Protocol driver uses middleware (application server) that


converts JDBC calls directly into the vendor-specific database calls.
• The same driver can be used for multiple databases a so it’s also known
as a Network-Protocol driver as well as a JAVA driver for database
middleware
•It is fully written in java.
Cont…
Advantage:
•There is no need for the vendor database library on the client machine
•Type 3 driver can be used in any web application as well as on internet also
because there is no any software require at client side
•Disadvantages:
•Network support is required on client machine.
•Requires database-specific coding to be done in the middle tier.
•Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
Type 4 Driver : Native-Protocol Driver(Pure Java driver directly
connected to database).
Cont…
•The JDBC type 4 driver converts JDBC method calls directly into the vendor
specific database calls
•it is known as thin driver.
•It is fully written in Java language.
•Sun provides a JDBC-ODBC Bridge driver by "com.mysql.jdbc.Driver“.
Cont…
Advantage:
•It’s a 100% pure JAVA Driver so it’s aplatform independence.
• No translation or middleware layers are used so consider as a faster than
other drivers.
•The all process of the application-to-database connection can manage by
JVM so the debugging is also managed easily
Disadvantage:
•There is a separate driver needed for each database at the client side.
• Drivers are Database dependent, as different database vendors use different
network protocols
JDBC Packages
The JDBC API is contained in two packages.
1. java.sql
2. javax.sql

java.sql package
•The first package is called java.sql and contains core JDBC interfaces of
the JDBC API.
•These include the JDBC interfaces that provide the basics for connecting
to the DBMS and interacting with data stored in the DBMS
•This package include classes and interface to perform almost all JDBC
operation such as creating and executing SQL Queries.
classes and interface of java.sql package
classes/interface Description
java.sql.Connection creates a connection with specific database
java.sql.CallableStatement Execute stored procedures

java.sql.Driver create an instance of a driver with the DriverManager.

java.sql.DriverManager This class loads the database drivers.


java.sql.PreparedStatement Used to create and execute parameterized query.

java.sql.ResultSet It is an interface that provide methods to access the result


row-by-row.
java.sql.SQLException Encapsulate all JDBC related exception.
java.sql.Statement This interface is used to execute SQL statements
javax.sql package
•This package is also known as JDBC extension API.
•It provides classes and interface to access server-side data
JDBC Process (or) Steps to connect a Java Application to Database

1. Loading the JDBC driver


2. Creating a Connection to Data Base
3. Creating a statement object
4. Executing SQL statements
5. Closing the connection
1. Loading the JDBC driver

•The JDBC driver must be loaded before the Java application can
connect to the DBMS.
•The Class.forName() method is used to load the JDBC driver
•Here forName() is a method of class Class.
•The driver is loaded by calling the Class.forName() method and
passing it the name of the driver
Class.forName("com.mysql.jdbc.Driver");
2. Creating a Connection to DataBase
•Once the driver is loaded, getConnection() method of DriverManager Class is
used to create a connection with the database.
•The Java application must connect to the DBMS using the
DriverManager.getConnection() method
Syntax:
getConnection(String url, String username, String password)
•url is the location of database.
• The DriverManager.getConnection() returns a Connection interface that is used
throughout the process to reference the database.
Example:
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/databasename","root","roo
t");
3. Creating a statement object

•The next step after the JDBC driver is loaded and a connection is
successfully made with a particular database is to send an SQL query to the
DBMS for processing.
•The statement object is responsible to execute queries with the database.
•createStatement() method of  Connection object is used create a
Statement object.
Example:
Statement stmt=con.createStatement();  
4. Executing a SQL statement
•The methods of Statement object is used to execute a query and return a
ResultSet object that contains the response from the DBMS.
Methods statement object:
executeQuery() is used for SELECT statement.
executeUpdate() is used for create, alter or drop table.
execute() is used when multiple results may be returned
Example:
String query="create table employee1(empid varchar(20),empname
varchar(30),empsal varchar(20))";
stmt.executeUpdate(query);
5. Closing the connection
•The close()method of Connection interface is used to close the
connection.
Con.close()
Example
import java.sql.*;
class create1
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="create table employee1(empid varchar(20),empname varchar(30),empsal
varchar(20))";
stmt.executeUpdate(query);
con.close();
}
}
Database Connection
•A Java application does not directly connect to a DBMS.
• Instead, the Java application connects with the JDBC driver that
is associated with the DBMS.
•However, before this connection is made, the JDBC driver must
be loaded and registered with the DriverManager.
•The purpose of loading and registering the JDBC driver is to bring
the JDBC driver into the Java Virtual Machine (JVM).
•The Class.forName() is used to load the JDBC driver.
•The Class.forName() throws a ClassNotFoundException if an error
occurs when loading the JDBC driver.
Cont …
•The connection to the database is established by using one of
three getConnection() methods of the DriverManager object.
•The getConnection() method requests access to the database
from the DBMS.
•It is up to the DBMS to grant or reject access.
•A Connection object is returned by the getConnection() method
if access is granted, otherwise the getConnection() method throws
an SQLException.
Cont …
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)

Example:
class create1
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/IIICSE","root","root");
}
Creating Table
import java.sql.*;
class create
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="create table employee(empid varchar(20) primary key,empname
varchar(30),empsal varchar(20))";
stmt.executeUpdate(query);
con.close();
}
}
Inserting data into Table
import java.sql.*;
class insertrow
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="insert into employee values(697,'ramireddy',59000)";
stmt.executeUpdate(query);
System.out.println("values inserted");
con.close();
}
}
Droping Tables
import java.sql.*;
class drop
{
public static void main(String [] args)throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="drop table student";
stmt.execute(query);
System.out.println("table is dropped");
con.close();
}
}
Updating Tables
import java.sql.*;
class update
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="update employee set esal=300000 where eid=1";
stmt.executeUpdate(query);
System.out.println("updated");
con.close();
}
}
Deleting data from tables
import java.sql.*;
class delete
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="delete from employee where eid=697";
stmt.executeUpdate(query);
System.out.println("deleted");
con.close();
}
}
ResultSet
•A ResultSet is a Java object that contains the results of an SQL query.
• In other words, it contains the rows that satisfy the conditions of the
query
•The executeQuery() method is used to send the query to the DBMS for
processing and returns a ResultSet object that contains data requested by
the query.
•The ResultSet object contains methods that are used to copy data from the
ResultSet into a Java variables for further processing.
• Data in a ResultSet object is logically organized into a virtual table
consisting of rows and columns.
•In addition to data, the ResultSet object also contains metadata, such as
column names, column size and column data type.
ResultSet
•The ResultSet uses a virtual cursor to point to a row of the virtual
table.
•The virtual cursor is positioned above the first row of data when
the ResultSet is returned by the executeQuery() method.
•The virtual cursor moved to the next row using the next()
method.
• next() method returns a boolean true if the row contains data,
otherwise a boolean false is returned, indicating that no more
rows exist in the ResultSet.
ResultSet
•Once the virtual cursor points to a row, the getXXX() method is
used to copy data from the row to a variable.
•For example, the getString() method is used to copy String data
from a column of the ResultSet.
• The getXXX() method requires one parameter, which is an
integer that represents the number of the column that contains
the data.
•For example, getString(1) copies the data from the first column
of the ResultSet.
Scrollable ResultSet
•Until the release of JDBC 2.1 API, the virtual cursor could only be moved
down the ResultSet object.
•But today the virtual cursor can be moved backwards or even positioned
at a specific row.
•The first() method moves the virtual cursor to the first row in the
ResultSet.
•The last() method positions the virtual cursor at the last row in the
ResultSet.
•The previous() method moves the virtual cursor to the previous row.
•The absolute() method positions the virtual cursor at the row number
specified by the integer passed as a parameter to the absolute() method.
•The getRow() method returns an integer that represents the number of
the current row in the ResultSet.
Scrollable ResultSet
•The Statement object that is created using the createStatement() of the
Connection object must be set up to handle a scrollable ResultSet by passing
the createStatement() method one of three constants.
• These constants are TYPE_FORWARD_ONLY,TYPE_SCROLL_INSENSITIVE,
and TYPE_SCROLL_SENSITIVE.
•The TYPE_FORWARD_ONLY constant restricts the virtual cursor to
downward movement.
• TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE constants
permit the virtual cursor to move in both directions.
Selecting data from tables
import java.sql.*;
class selectall
{
public static void main(String rags[])throws SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from employee");
while(rs.next())
{
System.out.println(rs.getInt(1) +" "+rs.getString(2)+" "+rs.getInt(3));
}
con.close();
}}
Example on Scrollable Result Set
import java.sql.*;
class select
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from employee");
rs.absolute(2);
System.out.println(rs.getString(1) +" "+rs.getString(2)+" "+rs.getInt(3));
con.close();
}
}
Statement Objects
The statement object is responsible to execute queries with the database.
There are 3 types of Statement Objects
1.Statement
2.Prepared Statement
3.Callable Statement
Any One of the three types of Statement objects is used to execute
the query.
Statement Object
•The Statement object is used whenever a Java application needs to
execute a query immediately without first having the query compiled.
•The statement object is responsible to execute queries with the database.
•createStatement() method of  Connection object is used create a
Statement object.
Example:
Statement stmt=con.createStatement(); 
•The Statement interface provides three different methods for executing
SQL statements, executeQuery(), executeUpdate(), and execute().
•The method executeQuery(String sql) is designed for SELECT statements
that returns result set  object .
Statement Object

•The method executeUpdate(String sql) is used to execute INSERT, UPDATE,


DELETE statements and also SQL DDL statements
like CREATE  and DROP . 
•The return value of executeUpdate() is an integer indicating the number of
rows that were affected.
•The method execute(String sql) is used to execute statements that return
more than one result set, more than one update count, or a combination
of the two
PreparedStatement Object
•A prepared statement is a feature used to execute the same (or
similar) SQL statements repeatwith high efficiencyedly.
•Use the when you plan to use the SQL statements many times.
The PreparedStatement interface accepts input parameters at
runtime
•It is used to execute parameterized query.
•The query is constructed similar to queries but a question mark
is used as a placeholder for a value that is inserted into the query
after the query is compiled.
insert into emp values(?,?,?)
•It is the value that changes each time the query is executed.
PreparedStatement Object

•The preparedStatement() method of the Connection object is


called to return the PreparedStatement object.
•The preparedStatement() method is passed the query that is
then precompiled.
PreparedStatement ps=con.prepareStatement("DELETE FROM
employee WHERE esal = ?");
•The setXXX() method of the PreparedStatement object is used to
replace the question mark with the value passed to the setXXX()
method.
PreparedStatement Object
•There are a number of setXXX() methods available in the
PreparedStatement object, each of which specifies the data type of
the value that is being passed to the setXXX() method
•The setXXX() requires two parameters. The first parameter is an
integer that identifies the position of the question mark
placeholder, and the second parameter is the value that replaces
the question mark placeholder.
setInt(1,id);
import java.sql.*;
import java.util.*;
class prepared
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
PreparedStatement ps=con.prepareStatement("insert into employee values(?,?,?)");
Scanner sc=new Scanner(System.in);
System.out.println("how many rows u want to insert");
int n=sc.nextInt();
while(n>0)
{
int id=sc.nextInt();
ps.setInt(1,id);
String name=sc.next();
ps.setString(2,name);
int sal=sc.nextInt();
ps.setInt(3,sal);
ps.executeUpdate();
n--;
}
con.close();}}
Write a JDBC program to delete records of an employee table whose id is 101 using Prepared Statement object and display the number
of rows deleted?
import java.sql.*;
import java.util.*;
class pre3
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
PreparedStatement ps=con.prepareStatement
("DELETE FROM employee WHERE eid= ?");
Scanner sc=new Scanner(System.in);
System.out.println("enter eid");
int sal=sc.nextInt();
ps.setInt(1,eid);
int n=ps.executeUpdate();
System.out.println("no of rows deleted“ +n);
con.close();
}
}
CallableStatement
•CallableStatement interface is used to call the stored procedures
and functions.
• A stored procedure is a block of code and is identified by a
unique name.
•The type and style of code depend on the DBMS vendor and can
be written in PL/SQL, TransactSQL, C, or another programming
language.
•The stored procedure is executed by invoking the name of the
stored procedure.
CallableStatement
•The CallableStatement object uses three types of parameters when
calling a stored procedure.
•These parameters are IN, OUT, and INOUT.
•The IN parameter contains any data that needs to be passed to the
stored procedure and whose value is assigned using the setXXX()
method
•The OUT parameter contains the value returned by the stored
procedures
•The INOUT parameter is a single parameter used for both passing
information to the stored procedure and retrieving information from a
stored procedure

You might also like