SlideShare a Scribd company logo
1 of 37
Download to read offline
Interacting with Database
ODBC
• Open Database Connectivity
• A standard or open application programming interface
(API) for accessing a database.
• ODBC provides a C interface for database access on
Windows environment.
JDBC
• JDBC stands for Java Database Connectivity.
• It is a standard Java API for connecting programs written in Java to
the data in relational databases.
• JDBC works with Java on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX.
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 (partially java driver)
 JDBC-Net pure Java/ Network-Protocol driver (fully
java driver)
 Pure Java Driver /Thin driver / Database-Protocol
driver(fully java driver)
JDBC-ODBC bridge driver
• The JDBC type 1 driver, also known as the 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.
• Advantages
• It allows us to communicate with all databases that supports ODBC driver
• It is vendor independent driver
• Disadvantages
• This driver is not portable because it is not written fully in Java.
• The performance is solver
Native API driver
• The JDBC type 2 driver, also known as the Native-API driver
• The Native API driver uses the client-side libraries of the database.
• The driver converts JDBC method calls into native calls of the database API.
• It is not written entirely in java.
• Advantages:
• Communicates faster as compared to type-1 Driver
• Contains additional features provided by specific database vendor
• Disadvantages:
• Mostly outdated
• Not thread safe
• If we change database need to change native api
JDBC-Net pure Java Driver
• The JDBC type 3 driver, also known as the Pure Java driver for database
middleware. It is a database driver implementation which makes use of a
middle tier between the calling program and the database.
• The middle-tier (application server) converts JDBC calls directly or indirectly into
a vendor-specific database protocol.
• It is fully written in java.
Type -3 [All java/ net protocol Driver ]
Advantages
1. No need for vendor specific library
2. Driver is written fully in java so portable
3. Suitable for web application
4. Type-3 driver so very small and fast to load
5. Driver is very flexible and allows access to multiple database using single driver.
Disadvantages:
1. Require another server application to install and maintain
2. Traversing the records may take longer ,since data comes through the backend
Thin driver
• The JDBC type 4 driver, also known as the Direct to Database Pure
Java Driver, is a database driver implementation that converts JDBC calls
directly into a vendor- specific database protocol.That is why it is known as thin
driver.
• It is fully written in Java language.
Type-4 Driver .
Advantages
1. Completely written in java so portable .
2. Most suitable for web applications
3. No of translation layer is less so performance is good.
4. Don’t need to install specific software on client or server.
Disadvantages
With type -4 drivers, user needs a different driver for each database.
JDBC two tier model
• In a two-tier model, a Java application communicates directly
with the database, via the JDBC driver.
• In a three-tier model, a Java application communicates with a middle tier
component that functions as an application server. The application server
talks to a given database using JDBC.
JDBC three tier model
Java.sql classes
Date : A thin wrapper around a millisecond value that allows JDBC to identify this as an
SQL DATE value.
DriverManager : The basic service for managing a set of JDBC drivers.
NOTE: The DataSource interface, new in the JDBC 2.0 API, provides another way to connect
to a data source.
DriverPropertyInfo : Driver properties for making a connection.
SQLPermission : The permission for which the SecurityManager will check when code that
is running an application with a SecurityManager enabled.
Time: A thin wrapper around the java.util.Date class that allows the JDBC API to identify this
as an SQL TIME value.
Timestamp: A thin wrapper around java.util.Date that allows the JDBC API to identify this as
an SQL TIMESTAMP value.
Types: The class that defines the constants that are used to identify generic SQL types,
called JDBC types.
Interfaces in java.sql package
Common JDBC Components
• The JDBC API provides the following interfaces
and classes −
• DriverManager Class
• Driver Interface
• Connection Interface
• Statement Interface
• ResultSet Interface
DriverManager Class
• The DriverManager class acts as an interface between user
and drivers.
• before interacting with a Database, it is a mandatory process
to register the driver; otherwise, an exception is thrown.
• 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().
Common JDBC Components
Method Description
public static void registerDriver(Driver driver); is used to register the given driver
with DriverManager.
public static void deregisterDriver(Driver driver);
is used to deregister the given
driver (drop the driver from the
list) with DriverManager.
public static Connection getConnection(String url); is used to establish the connection
with the specified url.
public static Connection getConnection(String
url,String userName,String password);
is used to establish the connection
with the specified url, username
and password.
Commonly used methods of DriverManager class
• Driver Interface
This interface handles the communications with the database
server.
You will very rarely interact directly with Driver objects.
Instead, you use DriverManager objects, which manages
objects of this type.
It also abstracts the details associated with working with
Driver objects.
• Connection Interface
It helps to establish a connection with the database.
A Connection is a session between a Java application and a database.
The Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData.
Commonly used methods of Connection interface
Method Description
public Statement createStatement(); creates a statement object that can be used to
execute SQL queries.
public void setAutoCommit(boolean
status);
It is used to set the commit status. By default
it is true.
public void commit(); It saves the changes made since the
previous commit/rollback permanent.
public void rollback(); Drops all changes made since the
previous commit/rollback.
public void close();
closes the connection and Releases a
JDBC resources immediately.
• Statement Interface
The Statement interface provides methods to
execute queries with the database.
It provides factory method to get the object
of ResultSet.
Method Description
public ResultSet executeQuery(String sql); used to execute SELECT query. It returns
the object of ResultSet.
public int executeUpdate(String sql); used to execute specified query, it may be
create, drop, insert, update, delete etc.
public boolean execute(String sql); used to execute queries that may return
multiple results.
public int[] executeBatch(); used to execute batch of commands.
Commonly used methods of Statement interface
• ResultSet Interface
The object of ResultSet maintains a cursor
pointing to a particular row of data.
Initially, cursor points to before the first row.
Method Description
public boolean next(); is used to move the cursor to the one row next from the
current position.
public boolean previous(); is used to move the cursor to the one row previous from
the current position.
public boolean first(); is used to move the cursor to the first row in result set
object.
public boolean last(); is used to move the cursor to the last row in result set
object.
public boolean absolute(int row); is used to move the cursor to the specified row number in
the ResultSet object.
public int getInt(int columnIndex); is used to return the data of specified column index of the
current row as int.
public int getInt(String columnName); is used to return the data of specified column name of
the current row as int.
public String getString(int columnIndex); is used to return the data of specified column index of the
current row as String.
public String getString(String columnName); is used to return the data of specified column name of
the current row as String.
Commonly used methods of ResultSet interface
Connecting to Database
• There are 5 steps to connect any java
application with the database in java using
JDBC. They are as follows:
1. Register the driver
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1.Register the driver class
• Class.forName()
• method 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 with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2. Creating connection
• The DriverManager .getConnection()
• method is used to establish connection with the database.
• Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password) throws
SQLException
• Example establish connection with Oracle Driver
• Connection con= DriverManager. getConnection( “jdbc:lodbc:DemoDB”, “username”,
“Password”)
3. Creating statement
• The createStatement()
• It is a 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 to create the statement object
Statement stmt=con.createStatement();
4. Executing queries
• The executeQuery()
• It is a 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 emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5. Closing 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();
Example to Connect Java Application
with mysql database
//program to create database
public class MyClass {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306","root","gpnanded" );
Statement stmt = con.createStatement();
int isCreated = stmt.executeUpdate("CREATE DATABASE AJP_DATABASE");
con.close();
}catch(Exception e){ System.out.print(e); }
} //main close
} //class close
public class CreateTableProgram {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/AJP_DATABASE","root","gpnand
ed" );
Statement stmt = con.createStatement();
int isCreated = stmt.executeUpdate("CREATE TABLE Employee1(Roll_no int , Name
varchar(20) , phone_no int)");
System.out.print("table created ");
con.close();
}catch(Exception e){System.out.print(e);}
}
}
public class DataInsertProgram {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/AJP_DATABASE", "root",
"gpnanded");
Statement stmt = con.createStatement();
int isCreated = stmt.executeUpdate("INSERT INTO student values (101,'Prashant',000)");
con.close();
} catch (Exception e) {System.out.print(e);}
}
}
import java.sql.*;
class MysqlCon{
public static void main(String args[])
{
Try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sun","root","root");
//here sun is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" " + rs.getString(3));
con.close();
}
catch(Exception e){System.out.println(e);}
}
}
The End

More Related Content

Similar to Unit 5.pdf

Similar to Unit 5.pdf (20)

JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
JDBC
JDBCJDBC
JDBC
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
jdbc
jdbcjdbc
jdbc
 
JDBC
JDBCJDBC
JDBC
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Jdbc
JdbcJdbc
Jdbc
 

Recently uploaded

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 

Recently uploaded (20)

young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 

Unit 5.pdf

  • 2. ODBC • Open Database Connectivity • A standard or open application programming interface (API) for accessing a database. • ODBC provides a C interface for database access on Windows environment.
  • 3. JDBC • JDBC stands for Java Database Connectivity. • It is a standard Java API for connecting programs written in Java to the data in relational databases. • JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
  • 4. 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 (partially java driver)  JDBC-Net pure Java/ Network-Protocol driver (fully java driver)  Pure Java Driver /Thin driver / Database-Protocol driver(fully java driver)
  • 5. JDBC-ODBC bridge driver • The JDBC type 1 driver, also known as the 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. • Advantages • It allows us to communicate with all databases that supports ODBC driver • It is vendor independent driver • Disadvantages • This driver is not portable because it is not written fully in Java. • The performance is solver
  • 6. Native API driver • The JDBC type 2 driver, also known as the Native-API driver • The Native API driver uses the client-side libraries of the database. • The driver converts JDBC method calls into native calls of the database API. • It is not written entirely in java. • Advantages: • Communicates faster as compared to type-1 Driver • Contains additional features provided by specific database vendor • Disadvantages: • Mostly outdated • Not thread safe • If we change database need to change native api
  • 7. JDBC-Net pure Java Driver • The JDBC type 3 driver, also known as the Pure Java driver for database middleware. It is a database driver implementation which makes use of a middle tier between the calling program and the database. • The middle-tier (application server) converts JDBC calls directly or indirectly into a vendor-specific database protocol. • It is fully written in java.
  • 8. Type -3 [All java/ net protocol Driver ] Advantages 1. No need for vendor specific library 2. Driver is written fully in java so portable 3. Suitable for web application 4. Type-3 driver so very small and fast to load 5. Driver is very flexible and allows access to multiple database using single driver. Disadvantages: 1. Require another server application to install and maintain 2. Traversing the records may take longer ,since data comes through the backend
  • 9. Thin driver • The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver implementation that converts JDBC calls directly into a vendor- specific database protocol.That is why it is known as thin driver. • It is fully written in Java language.
  • 10. Type-4 Driver . Advantages 1. Completely written in java so portable . 2. Most suitable for web applications 3. No of translation layer is less so performance is good. 4. Don’t need to install specific software on client or server. Disadvantages With type -4 drivers, user needs a different driver for each database.
  • 11. JDBC two tier model • In a two-tier model, a Java application communicates directly with the database, via the JDBC driver.
  • 12. • In a three-tier model, a Java application communicates with a middle tier component that functions as an application server. The application server talks to a given database using JDBC. JDBC three tier model
  • 13. Java.sql classes Date : A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. DriverManager : The basic service for managing a set of JDBC drivers. NOTE: The DataSource interface, new in the JDBC 2.0 API, provides another way to connect to a data source. DriverPropertyInfo : Driver properties for making a connection. SQLPermission : The permission for which the SecurityManager will check when code that is running an application with a SecurityManager enabled. Time: A thin wrapper around the java.util.Date class that allows the JDBC API to identify this as an SQL TIME value. Timestamp: A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. Types: The class that defines the constants that are used to identify generic SQL types, called JDBC types.
  • 15.
  • 16. Common JDBC Components • The JDBC API provides the following interfaces and classes − • DriverManager Class • Driver Interface • Connection Interface • Statement Interface • ResultSet Interface
  • 17. DriverManager Class • The DriverManager class acts as an interface between user and drivers. • before interacting with a Database, it is a mandatory process to register the driver; otherwise, an exception is thrown. • 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(). Common JDBC Components
  • 18. Method Description public static void registerDriver(Driver driver); is used to register the given driver with DriverManager. public static void deregisterDriver(Driver driver); is used to deregister the given driver (drop the driver from the list) with DriverManager. public static Connection getConnection(String url); is used to establish the connection with the specified url. public static Connection getConnection(String url,String userName,String password); is used to establish the connection with the specified url, username and password. Commonly used methods of DriverManager class
  • 19. • Driver Interface This interface handles the communications with the database server. You will very rarely interact directly with Driver objects. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.
  • 20. • Connection Interface It helps to establish a connection with the database. A Connection is a session between a Java application and a database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData.
  • 21. Commonly used methods of Connection interface Method Description public Statement createStatement(); creates a statement object that can be used to execute SQL queries. public void setAutoCommit(boolean status); It is used to set the commit status. By default it is true. public void commit(); It saves the changes made since the previous commit/rollback permanent. public void rollback(); Drops all changes made since the previous commit/rollback. public void close(); closes the connection and Releases a JDBC resources immediately.
  • 22. • Statement Interface The Statement interface provides methods to execute queries with the database. It provides factory method to get the object of ResultSet.
  • 23. Method Description public ResultSet executeQuery(String sql); used to execute SELECT query. It returns the object of ResultSet. public int executeUpdate(String sql); used to execute specified query, it may be create, drop, insert, update, delete etc. public boolean execute(String sql); used to execute queries that may return multiple results. public int[] executeBatch(); used to execute batch of commands. Commonly used methods of Statement interface
  • 24. • ResultSet Interface The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row.
  • 25. Method Description public boolean next(); is used to move the cursor to the one row next from the current position. public boolean previous(); is used to move the cursor to the one row previous from the current position. public boolean first(); is used to move the cursor to the first row in result set object. public boolean last(); is used to move the cursor to the last row in result set object. public boolean absolute(int row); is used to move the cursor to the specified row number in the ResultSet object. public int getInt(int columnIndex); is used to return the data of specified column index of the current row as int. public int getInt(String columnName); is used to return the data of specified column name of the current row as int. public String getString(int columnIndex); is used to return the data of specified column index of the current row as String. public String getString(String columnName); is used to return the data of specified column name of the current row as String. Commonly used methods of ResultSet interface
  • 26. Connecting to Database • There are 5 steps to connect any java application with the database in java using JDBC. They are as follows: 1. Register the driver 2. Creating connection 3. Creating statement 4. Executing queries 5. Closing connection
  • 27. 1.Register the driver class • Class.forName() • method 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 with JDBC-ODBC Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  • 28. 2. Creating connection • The DriverManager .getConnection() • method is used to establish connection with the database. • Syntax of getConnection() method public static Connection getConnection(String url)throws SQLException public static Connection getConnection(String url,String name,String password) throws SQLException • Example establish connection with Oracle Driver • Connection con= DriverManager. getConnection( “jdbc:lodbc:DemoDB”, “username”, “Password”)
  • 29. 3. Creating statement • The createStatement() • It is a 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 to create the statement object Statement stmt=con.createStatement();
  • 30. 4. Executing queries • The executeQuery() • It is a 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 emp"); while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
  • 31. 5. Closing 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();
  • 32. Example to Connect Java Application with mysql database
  • 33. //program to create database public class MyClass { public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","gpnanded" ); Statement stmt = con.createStatement(); int isCreated = stmt.executeUpdate("CREATE DATABASE AJP_DATABASE"); con.close(); }catch(Exception e){ System.out.print(e); } } //main close } //class close
  • 34. public class CreateTableProgram { public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/AJP_DATABASE","root","gpnand ed" ); Statement stmt = con.createStatement(); int isCreated = stmt.executeUpdate("CREATE TABLE Employee1(Roll_no int , Name varchar(20) , phone_no int)"); System.out.print("table created "); con.close(); }catch(Exception e){System.out.print(e);} } }
  • 35. public class DataInsertProgram { public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/AJP_DATABASE", "root", "gpnanded"); Statement stmt = con.createStatement(); int isCreated = stmt.executeUpdate("INSERT INTO student values (101,'Prashant',000)"); con.close(); } catch (Exception e) {System.out.print(e);} } }
  • 36. import java.sql.*; class MysqlCon{ public static void main(String args[]) { Try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sun","root","root"); //here sun is database name, root is username and password Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2)+" " + rs.getString(3)); con.close(); } catch(Exception e){System.out.println(e);} } }