SlideShare a Scribd company logo
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

More Related Content

PPT
Basic Java Database Connectivity(JDBC)
PPT
Jdbc complete
PPT
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
PPS
Jdbc architecture and driver types ppt
PDF
Overview Of JDBC
DOC
jdbc document
Basic Java Database Connectivity(JDBC)
Jdbc complete
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
Jdbc architecture and driver types ppt
Overview Of JDBC
jdbc document

What's hot (20)

PPTX
Jdbc drivers
PPT
Jdbc (database in java)
PPT
PPTX
Java- JDBC- Mazenet Solution
PPT
Jdbc slide for beginers
PPTX
Java Database Connectivity (JDBC)
PPTX
Jdbc_ravi_2016
PPT
PDF
Ajp notes-chapter-05
PPT
Jdbc drivers
PPTX
java Jdbc
PPT
JDBC Architecture and Drivers
PDF
Database and Java Database Connectivity
PPT
PPT
Java database connectivity
PPTX
Database Access With JDBC
PPT
JDBC Connectivity Model
PPSX
JDBC: java DataBase connectivity
Jdbc drivers
Jdbc (database in java)
Java- JDBC- Mazenet Solution
Jdbc slide for beginers
Java Database Connectivity (JDBC)
Jdbc_ravi_2016
Ajp notes-chapter-05
Jdbc drivers
java Jdbc
JDBC Architecture and Drivers
Database and Java Database Connectivity
Java database connectivity
Database Access With JDBC
JDBC Connectivity Model
JDBC: java DataBase connectivity
Ad

Viewers also liked (12)

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

Similar to Core jdbc basics (20)

PPTX
PPT
JDBC.ppt
PPT
Jdbc connectivity
PDF
Unit 5.pdf
PPT
Java database connectivity
PPT
JDBC java for learning java for learn.ppt
PPTX
Java Database Connectivity by shreyash simu dbce.pptx
PPTX
Jdbc introduction
PPT
4-INTERDUCATION TO JDBC-2019.ppt
PPTX
Java Data Base Connectivity concepts.pptx
PDF
PDF
JDBC Presentation with JAVA code Examples.pdf
PDF
Chapter 5 JDBC.pdf for stufent of computer andtudent It s
PPT
jdbc_presentation.ppt
PPT
PPTX
java.pptx
PPT
Chap3 3 12
PPTX
Java database connectivity with MySql
JDBC.ppt
Jdbc connectivity
Unit 5.pdf
Java database connectivity
JDBC java for learning java for learn.ppt
Java Database Connectivity by shreyash simu dbce.pptx
Jdbc introduction
4-INTERDUCATION TO JDBC-2019.ppt
Java Data Base Connectivity concepts.pptx
JDBC Presentation with JAVA code Examples.pdf
Chapter 5 JDBC.pdf for stufent of computer andtudent It s
jdbc_presentation.ppt
java.pptx
Chap3 3 12
Java database connectivity with MySql

Recently uploaded (20)

PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Digital Strategies for Manufacturing Companies
PPT
Introduction Database Management System for Course Database
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Become an Agentblazer Champion Challenge Kickoff
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
medical staffing services at VALiNTRY
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
AI in Product Development-omnex systems
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PPTX
L1 - Introduction to python Backend.pptx
PPTX
ai tools demonstartion for schools and inter college
Upgrade and Innovation Strategies for SAP ERP Customers
Softaken Excel to vCard Converter Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Digital Strategies for Manufacturing Companies
Introduction Database Management System for Course Database
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
Online Work Permit System for Fast Permit Processing
Which alternative to Crystal Reports is best for small or large businesses.pdf
Become an Agentblazer Champion Challenge Kickoff
ManageIQ - Sprint 268 Review - Slide Deck
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
A REACT POMODORO TIMER WEB APPLICATION.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
medical staffing services at VALiNTRY
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
AI in Product Development-omnex systems
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
L1 - Introduction to python Backend.pptx
ai tools demonstartion for schools and inter college

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.