SlideShare una empresa de Scribd logo
1 de 32
Core JDBC Basics
Sourabrata Mukherjee
Topics:
1. What is JDBC
2. Why Use JDBC and not ODBC?
3. JDBC Architecture
4. Steps to connect to the database using java
5. JDBC Driver and it’s Types
6. JDBC Connection
7. JDBC Statements
JDBC and It’s Architecture
● The JDBC (Java Database Connectivity) API defines interfaces and classes
for writing database applications in Java by making database connections.
Using JDBC you can send SQL, PL/SQL statements to almost any relational
database. JDBC is a Java API for executing SQL statements and supports
basic SQL functionality. It provides RDBMS access by allowing you to embed
SQL inside Java code.
Continue..
● JDBC standardizes how to connect to a database, how to execute queries
against it, how to navigate the result of such a query, and how to execute
updates in the database.
● Although JDBC was designed specifically to provide a Java interface to
relational databases, you may find that you need to write Java code to access
non-relational databases as well.
Why use JDBC and not ODBC?
Before JDBC, ODBC API was the database API to connect and execute query with
the database. But, 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).
* API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other.
JDBC Architecture
In general, JDBC Architecture consists of two layers − JDBC API: This provides the
application-to-JDBC Manager connection. JDBC Driver API: This supports the
JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and
database-specific drivers to provide transparent connectivity to heterogeneous
databases.
Steps to connect to the database using java
Register the driver class The forName() method of Class class is used to
register the driver class. This method is used to dynamically load the driver
class.
Class.forName("com.mysql.jdbc.Driver");
Continue..
Create the connection object The getConnection() method of DriverManager
class 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
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/SOURODB","root","souro");
Continue..
Create the Statement object The createStatement() method of Connection
interface is used to create statement. The object of statement is responsible
to execute queries with the database.
Statement stmt=con.createStatement();
Continue..
Execute the query The executeQuery() method of Statement interface is used to
execute queries to the database. This method returns the object of ResultSet
that can be used to get all the records of a table.
ResultSet rs=stmt.executeQuery("SELECT EmpID,LastName,FirstName,Address,City FROM
EMPLOYEE");
Continue..
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.
con.close();
JDBC Driver and It’s Types
A JDBC driver is a collection of Java classes that enables you to connect to a certain
database. For instance, MySQL will have its own JDBC driver. A JDBC driver implements a
lot of the JDBC API interfaces. When your code uses a given JDBC driver, it actually just
uses the standard JDBC interfaces. The concrete JDBC driver used is hidden behind the
JDBC interfaces.
There are 4 types of JDBC drivers:
● JDBC-ODBC bridge driver
● Native-API driver
● Network Protocol driver
● Thin driver
Continue..
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. This is now
discouraged because of thin driver.
Continue..
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.
Continue..
Native-API driver - JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors and
used in the same manner as the JDBC-ODBC Bridge.
Continue..
Advantage:
Performance upgrade 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.
Continue..
Network Protocol driver - The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.
Continue..
Advantage:
No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
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.
Continue..
Thin driver - The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.
Continue..
Advantage:
Better performance than all other drivers. No software is required at client side
or server side.
Disadvantage:
Drivers depends on the Database.
Continue..
Which Driver should be used when?
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 Connection
Once a JDBC driver is loaded and initialized, you need to connect to the database. You
do so by obtaining a Connection to the database via the JDBC API and the loaded
driver. All communication with the database happens via a connection. An application
can have more than one connection open to a database at a time. This is actually very
common.
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.
JDBC Statements
A Statement is what you use to execute queries against the database. There are a
few different types of statements you can use. Each statement corresponds to a
single query.
Once a connection is obtained we can interact with the database. The JDBC
Statement, CallableStatement, and PreparedStatement interfaces define the
methods and properties that enable you to send SQL or PL/SQL commands
Continue..
Each interface's purpose -
Interface Recommended Use
Statement Use for general-purpose access to your database. Useful when you
are using static SQL statements at runtime. The Statement interface
cannot accept parameters.
PreparedStatement Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access the database stored procedures. The
CallableStatement interface can also accept runtime input
parameters.
Continue..
The important methods of Statement interface are as follows:
public ResultSet executeQuery(String sql): is used to execute SELECT query. It
returns the object of ResultSet.
public int executeUpdate(String sql): is used to execute specified query, it may
be create, drop, insert, update, delete etc.
public boolean execute(String sql): is used to execute queries that may return
multiple results.
public int[] executeBatch(): is used to execute batch of commands.
JDBC Result Sets
When you perform a query against the database you get back a ResultSet. You can
then traverse this ResultSet to read the result of the query.
The object of ResultSet maintains a cursor pointing to a particular row of data.
Initially, cursor points to before the first row.
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
Continue..
Commonly used methods of ResultSet interface -
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.
Continue..
public boolean relative(int row): is used to move the cursor to the relative row
number in the ResultSet object, it may be positive or negative.
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
JDBC Transaction
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.
Continue..
If your JDBC Connection is in autocommit mode, which it is by default, then every
SQL statement is committed to the database upon its completion.
Transactions enable you to control if, and when, changes are applied to the
database.
To enable manual- transaction support instead of the auto-commit mode that the
JDBC driver uses by default, use the Connection object's setAutoCommit()
method. If you pass a boolean false to setAutoCommit( ), you turn off auto-
commit. You can pass a boolean true to turn it back on again.
Conclusion
Thank You

Más contenido relacionado

La actualidad más candente

Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
Ambarish Rai
 

La actualidad más candente (20)

Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc
JdbcJdbc
Jdbc
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Model
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 

Destacado

Kelly S. Lamb Resume
Kelly S. Lamb ResumeKelly S. Lamb Resume
Kelly S. Lamb Resume
Kelly Lamb
 
Resume_KaiYanTan
Resume_KaiYanTanResume_KaiYanTan
Resume_KaiYanTan
Kai Yan Tan
 

Destacado (13)

Doc1
Doc1Doc1
Doc1
 
Comunicación Interactiva.
Comunicación Interactiva.Comunicación Interactiva.
Comunicación Interactiva.
 
Tallinn tartu 30.11.2016
Tallinn tartu 30.11.2016Tallinn tartu 30.11.2016
Tallinn tartu 30.11.2016
 
informatiefolder
informatiefolderinformatiefolder
informatiefolder
 
SOLOMOTO_10 советов о том, как заставить ваш бизнес продавать через интернет:...
SOLOMOTO_10 советов о том, как заставить ваш бизнес продавать через интернет:...SOLOMOTO_10 советов о том, как заставить ваш бизнес продавать через интернет:...
SOLOMOTO_10 советов о том, как заставить ваш бизнес продавать через интернет:...
 
Vancouver island outing part 2
Vancouver island outing part 2Vancouver island outing part 2
Vancouver island outing part 2
 
Kelly S. Lamb Resume
Kelly S. Lamb ResumeKelly S. Lamb Resume
Kelly S. Lamb Resume
 
Resume_KaiYanTan
Resume_KaiYanTanResume_KaiYanTan
Resume_KaiYanTan
 
бюджет 2016 ключові риси-11 грудня
бюджет 2016 ключові риси-11 груднябюджет 2016 ключові риси-11 грудня
бюджет 2016 ключові риси-11 грудня
 
Proyecto Eratostenes
Proyecto EratostenesProyecto Eratostenes
Proyecto Eratostenes
 
The Economics of Scrum - Finance and Capitalization
The Economics of Scrum - Finance and CapitalizationThe Economics of Scrum - Finance and Capitalization
The Economics of Scrum - Finance and Capitalization
 
Balmoral Group - SPE Offshore Europe
Balmoral Group - SPE Offshore EuropeBalmoral Group - SPE Offshore Europe
Balmoral Group - SPE Offshore Europe
 
Expro - SPE Offshore Europe Case Study
Expro - SPE Offshore Europe Case StudyExpro - SPE Offshore Europe Case Study
Expro - SPE Offshore Europe Case Study
 

Similar a Core jdbc basics

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
kingkolju
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
backdoor
 

Similar a Core jdbc basics (20)

Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
jdbc
jdbcjdbc
jdbc
 
JDBC
JDBCJDBC
JDBC
 
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
Jdbc
JdbcJdbc
Jdbc
 
java.pptx
java.pptxjava.pptx
java.pptx
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbms
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
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
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
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 with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
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
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 

Último

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Último (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Core jdbc basics

  • 2. Topics: 1. What is JDBC 2. Why Use JDBC and not ODBC? 3. JDBC Architecture 4. Steps to connect to the database using java 5. JDBC Driver and it’s Types 6. JDBC Connection 7. JDBC Statements
  • 3. JDBC and It’s Architecture ● The JDBC (Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code.
  • 4. Continue.. ● JDBC standardizes how to connect to a database, how to execute queries against it, how to navigate the result of such a query, and how to execute updates in the database. ● Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.
  • 5. Why use JDBC and not ODBC? Before JDBC, ODBC API was the database API to connect and execute query with the database. But, 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). * API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other.
  • 6. JDBC Architecture In general, JDBC Architecture consists of two layers − JDBC API: This provides the application-to-JDBC Manager connection. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.
  • 7. Steps to connect to the database using java Register the driver class The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class. Class.forName("com.mysql.jdbc.Driver");
  • 8. Continue.. Create the connection object The getConnection() method of DriverManager class 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 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/SOURODB","root","souro");
  • 9. Continue.. Create the Statement object The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database. Statement stmt=con.createStatement();
  • 10. Continue.. Execute the query The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table. ResultSet rs=stmt.executeQuery("SELECT EmpID,LastName,FirstName,Address,City FROM EMPLOYEE");
  • 11. Continue.. 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. con.close();
  • 12. JDBC Driver and It’s Types A JDBC driver is a collection of Java classes that enables you to connect to a certain database. For instance, MySQL will have its own JDBC driver. A JDBC driver implements a lot of the JDBC API interfaces. When your code uses a given JDBC driver, it actually just uses the standard JDBC interfaces. The concrete JDBC driver used is hidden behind the JDBC interfaces. There are 4 types of JDBC drivers: ● JDBC-ODBC bridge driver ● Native-API driver ● Network Protocol driver ● Thin driver
  • 13. Continue.. 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. This is now discouraged because of thin driver.
  • 14. Continue.. 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.
  • 15. Continue.. Native-API driver - JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge.
  • 16. Continue.. Advantage: Performance upgrade 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.
  • 17. Continue.. Network Protocol driver - The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.
  • 18. Continue.. Advantage: No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc. 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.
  • 19. Continue.. Thin driver - The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.
  • 20. Continue.. Advantage: Better performance than all other drivers. No software is required at client side or server side. Disadvantage: Drivers depends on the Database.
  • 21. Continue.. Which Driver should be used when? 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.
  • 22. JDBC Connection Once a JDBC driver is loaded and initialized, you need to connect to the database. You do so by obtaining a Connection to the database via the JDBC API and the loaded driver. All communication with the database happens via a connection. An application can have more than one connection open to a database at a time. This is actually very common. 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.
  • 23. JDBC Statements A Statement is what you use to execute queries against the database. There are a few different types of statements you can use. Each statement corresponds to a single query. Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands
  • 24. Continue.. Each interface's purpose - Interface Recommended Use Statement Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters. PreparedStatement Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime. CallableStatement Use when you want to access the database stored procedures. The CallableStatement interface can also accept runtime input parameters.
  • 25. Continue.. The important methods of Statement interface are as follows: public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc. public boolean execute(String sql): is used to execute queries that may return multiple results. public int[] executeBatch(): is used to execute batch of commands.
  • 26. JDBC Result Sets When you perform a query against the database you get back a ResultSet. You can then traverse this ResultSet to read the result of the query. The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row. 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
  • 27. Continue.. Commonly used methods of ResultSet interface - 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.
  • 28. Continue.. public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative. 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
  • 29. JDBC Transaction 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. Continue.. If your JDBC Connection is in autocommit mode, which it is by default, then every SQL statement is committed to the database upon its completion. Transactions enable you to control if, and when, changes are applied to the database. To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto- commit. You can pass a boolean true to turn it back on again.