SlideShare a Scribd company logo
1 of 32
JAVA Database Connectivity
(JDBC)
Dr. Satish M.,
Associate Professor – CSE,
GMRIT, Rajam
JSP application development: Conditional processing
display values using an expression to set an attribute,
Declaring variables and methods, sharing data between
JSP pages, Requests and users passing control and data
between pages, Sharing sessions and application data,
memory usage considerations
Database Access: Database Programming using JDBC,
javax.sql. package; Accessing MySQL database- Accessing
MS Access database- Accessing a Database from a Html
Page
JSP Custom tags-Custom tag API-Custom URI
UNIT-IV 10+3 hours
Introduction
JDBC is a Java language API that provides access
to databases which utilize the Structured Query
Language(SQL)
SQL DB applications can be entirely written in
Java.
The majority of the code of these applications can
be database neutral by utilizing the SQL that is not
vendor specific
Application Architecture
Client (User
Interface)
JDBC
Data
base
Two-Tier Architecture
Middle Tier
(Business Logic)
JDBC
Data
base
Three-Tier Architecture
Client (User
Interface)
JSP /
Servlets
/EJB
HTTP/
RMI/
CORBA
HTML/
JavaScri
-pt/XML
Two-Tier Model
Three-tier Model
JDBC Driver
A JDBC driver implements the interface to a
particular database
This allows you to develop your program in a
database-independent way and connect to a
specific database engine by plugging in the
appropriate JDBC driver at deployment time
There are several kinds of JDBC drivers
JDBC-ODBC bridge drivers are useful for small
business applications
ODBC(Open Database Connectivity) is a
technology developed by Microsoft to allow
generic access to a DBMS on Windows platform
JDBC Driver Types
The four structurally different types of JDBC
drivers are as follows:
Type 1: JDBC-ODBC bridge plus ODBC
driver
Type 2: Native-API partly Java driver
Type 3:JDBC-Net pure Java driver
Type 4: Native-protocol pure Java driver
Type 1: JDBC-ODBC bridge
plus ODBC driver
The JDBC-ODBC bridge product provides
JDBC access via ODBC drivers. ODBC
(Open Database Connectivity) predates
JDBC and is widely used to connect to
databases in a non-Java environment.
ODBC is probably the most widely available
programming interface for accessing
relational databases.
Type 2: Native-API
partly Java driver
Type 2 drivers use a native API to communicate with a
database system. Java Native methods are used to
invoke the API functions that perform database
operations. A big advantage of Type 2 drivers is that
they are generally faster than Type 1 drivers.
The primary disadvantages of Type 2 drivers are as
follows:
Type 2 drivers require native code on the target
machine.
The Java Native Interface on which they depend is not
consistently implemented among different vendors of
Java virtual machines.
Type 3:JDBC-Net pure
Java driver
Type 3 drivers translate JDBC calls into a DBMS
independent net protocol that is then translated to
a DBMS protocol by a server.
Advantages of Type 3 drivers are the following:
Type 3 drivers do not require any native binary
code on the client.
Type 3 drivers do not need client installation.
Type 3 drivers support several networking
options, such as HTTP tunneling.
A major drawback of Type 3 drivers is that they
can be difficult to set up since the architecture is
complicated by the network interface.
Type 4: Native-protocol
pure Java driver
The Type 4 driver is a native protocol, 100-
percent Java driver. This allows direct calls from
a Java client to a DBMS server. Because the
Type 4 driver is written in 100-percent Java, it
requires no configuration on the client machine
other than telling your application where to find
the driver.
This allows a direct call from the client machine
to the DBMS server. Many of these protocols are
proprietary, so these drivers are provided by the
database vendors themselves.
JDBC Architecture
Java
application
JDBC-
Driver manager
Native
Protocol driver
JDBC-
Net-driver
Native
API-driver
JDBC-ODBC
bridge
Client library
DB-
Middleware
ODBC
Client library
JDBC-API
Driver selection is based on the architecture of the
application (Two-tier vs Three-tier) and tradeoffs of
speed, portability and reliability
Steps required to Access DB
Driver Manager
The java.sql.DriverManager provides basic
services for managing JDBC drivers During
initialization, the DriverManager attempts to load
the driver classes referenced in the "jdbc.drivers"
system property.
Alternatively, a program can explicitly load JDBC
drivers at any time using Class.forName(). This
allows a user to customize the JDBC drivers their
applications use.
A newly loaded driver class should call
registerDriver() to make itself known to the
DriverManager. Usually, the driver does this
internally.
ODBC Data Source Administrator
You can use ODBC Data Source Administrator to
configure your applications so that they can get data
from a variety of database management systems.
Using Data Sources (ODBC)
You can use Data Sources Open Database Connectivity
(ODBC) to access data from a variety of database
management systems. For example, if you have a
program that accesses data in a SQL database, Data
Sources (ODBC) will let you use the same program to
access data in a Visual FoxPro database. To do this, you
must add software components called drivers to your
system. Data Sources (ODBC) helps you add and
configure these drivers.
Loading a Driver
import java.sql.* ;
Import the Java
SQL packages
Load the JDBC Driver
class SampleJDBC
{
public static void main(String args[])
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
/* throws ClassNotFoundException, if the class
can’t be located */
Connection
A Connection object represents a connection
with a database. A connection session
includes the SQL statements that are
executed and the results that are returned
over that connection.
A single application can have one or more
connections with a single database, or it can
have connections with many different
databases.
Opening a connection
The standard way to establish a
connection with a database is to call the
method getConnection() on either a
DataSource or a DriverManager. The
Driver method connect uses this URL to
establish the connection.
Connecting to the Database
Connection c =
DriverManager.getConnection("jdbc:odbc:acc");
/* Connection c =
DriverManager.getConnection("jdbc:odbc:ora",
"scott", "tiger"); */
/* The DriverManager will select
the appropriate driver and setup
the DB connection */ Connecting to database
SQL Statements
Once a connection is established, it is used to
pass SQL statements to the database. Since
there are no restrictions imposed on the kinds of
SQL statements that may be sent to a DBMS
using JDBC, the user has a great deal of
flexibility to use database-specific statements or
even non-SQL statements.
The JDBC core API provides these three classes
for sending SQL statements to the database:
SQL Statements cont…
Statement: A Statement object is used for
sending simple SQL statements. Statements are
created by the method createStatement().
PreparedStatement: A PreparedStatement is a
SQL statement that is precompiled and stored in
a PreparedStatement object. This object can
then be used to execute this statement multiple
times.
CallableStatement: CallableStatement is used
to execute SQL stored procedures.
CallableStatements are created by the method
prepareCall().
Creating a statement
Statement s = c.createStatement();
/* A JDBC Statement object has methods that can be
used to:
- execute SQL queries (SELECT)
- execute SQL DML commands (INSERT,
UPDATE, DELETE) and DDL commands
(CREATE TABLE, ALTER TABLE,
DROP TABLE) */
Create a statement
Executing SQL Query
ResultSet rs=s.executeQuery("select sid, sname,
rating from Sailors");
s.executeUpdate("insert into Sailors values
(80,'ravi',6, 23)");
Executing a query
Inserting a row
Processing Resultset
while(rs.next())
{
System.out.println("n"+rs.getInt(1) + "t" +
rs.getString(2) + "t" + rs.getInt(3));
}
Processing Resultset
/* A result set can be viewed as a table of data
containing rows as a result of a query */
Retrieving Data
Individual columns values are read using one of
the getXXX() methods. (e.g. getString(), getInt(),
getFloat(), getDate(), etc.)
There are two versions of each getXXX() method:
• one that takes the case-insensitive String name
of the column
• one that takes an SQL-style column index
column numbers begin at 1
ex: s = rs.getString(1);
s = rs.getString(“sname”);
ResultSet MetaData
ResultSetMetaData rm=rs.getMetaData();
/* Metadata is data about data.
The resultset metadata contains
information about the columns
in the result set */
for(int i=1;i<=rm.getColumnCount();i++)
System.out.print(rm.getColumnName(i)+ "t");
Retrieving Column Info
No.of Columns &
Names of Columns
Releasing Resources
rs.close();
s.close();
c.close();
Releasing Resources
/* All methods of Connection, Statement, ResultSet &
other JDBC API may throw SQLException */
Summary
Load Driver
Connecting to the database
Create Statement
Execute Statement
Process Resultset
More
results ?
Release Resources
no
yes
Prepared Statements
If executing similar SQL statements multiple
times, using “prepared statement” may be more
efficient
Statement is created in standard form that is sent
to the database for compilation before actually
being used
Each time you use it, you simply replace some of
the marked parameters using the setXxx methods
Conclusion
Through JDBC we can create very good
Java applications which need to access
databases
JDBC is used with JSP/EJB to create web
applications
Than ‘Q’ ueries?

More Related Content

Similar to JDBC.ppt

Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 

Similar to JDBC.ppt (20)

Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc
jdbcjdbc
jdbc
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
java.pptx
java.pptxjava.pptx
java.pptx
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
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
JdbcJdbc
Jdbc
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
JDBC
JDBCJDBC
JDBC
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
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
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 

More from ChagantiSahith (8)

8086_architecture.ppt
8086_architecture.ppt8086_architecture.ppt
8086_architecture.ppt
 
erp.pptx
erp.pptxerp.pptx
erp.pptx
 
ERP.pptx
ERP.pptxERP.pptx
ERP.pptx
 
ENCh26.ppt
ENCh26.pptENCh26.ppt
ENCh26.ppt
 
SUSTAINABLE DEVELOPMENT GOALS.pptx
SUSTAINABLE    DEVELOPMENT    GOALS.pptxSUSTAINABLE    DEVELOPMENT    GOALS.pptx
SUSTAINABLE DEVELOPMENT GOALS.pptx
 
UNIT-II-Probability-ConditionalProbability-BayesTherom.pptx
UNIT-II-Probability-ConditionalProbability-BayesTherom.pptxUNIT-II-Probability-ConditionalProbability-BayesTherom.pptx
UNIT-II-Probability-ConditionalProbability-BayesTherom.pptx
 
HCF & LCM (1).pptx
HCF & LCM (1).pptxHCF & LCM (1).pptx
HCF & LCM (1).pptx
 
POLITY.pptx
POLITY.pptxPOLITY.pptx
POLITY.pptx
 

Recently uploaded

Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan CytotecJual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
ZurliaSoop
 
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pillsMifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Abortion pills in Kuwait Cytotec pills in Kuwait
 
Structuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdfStructuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdf
laloo_007
 
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in OmanMifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
instagramfab782445
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
daisycvs
 

Recently uploaded (20)

Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan CytotecJual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
PHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation FinalPHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation Final
 
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
 
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NSCROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperity
 
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAIGetting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
 
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
 
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Buy gmail accounts.pdf buy Old Gmail Accounts
Buy gmail accounts.pdf buy Old Gmail AccountsBuy gmail accounts.pdf buy Old Gmail Accounts
Buy gmail accounts.pdf buy Old Gmail Accounts
 
Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business Growth
 
Buy Verified TransferWise Accounts From Seosmmearth
Buy Verified TransferWise Accounts From SeosmmearthBuy Verified TransferWise Accounts From Seosmmearth
Buy Verified TransferWise Accounts From Seosmmearth
 
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pillsMifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
 
Structuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdfStructuring and Writing DRL Mckinsey (1).pdf
Structuring and Writing DRL Mckinsey (1).pdf
 
Falcon Invoice Discounting: Aviate Your Cash Flow Challenges
Falcon Invoice Discounting: Aviate Your Cash Flow ChallengesFalcon Invoice Discounting: Aviate Your Cash Flow Challenges
Falcon Invoice Discounting: Aviate Your Cash Flow Challenges
 
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in OmanMifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 
Falcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial WingsFalcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial Wings
 

JDBC.ppt

  • 1. JAVA Database Connectivity (JDBC) Dr. Satish M., Associate Professor – CSE, GMRIT, Rajam
  • 2. JSP application development: Conditional processing display values using an expression to set an attribute, Declaring variables and methods, sharing data between JSP pages, Requests and users passing control and data between pages, Sharing sessions and application data, memory usage considerations Database Access: Database Programming using JDBC, javax.sql. package; Accessing MySQL database- Accessing MS Access database- Accessing a Database from a Html Page JSP Custom tags-Custom tag API-Custom URI UNIT-IV 10+3 hours
  • 3. Introduction JDBC is a Java language API that provides access to databases which utilize the Structured Query Language(SQL) SQL DB applications can be entirely written in Java. The majority of the code of these applications can be database neutral by utilizing the SQL that is not vendor specific
  • 4. Application Architecture Client (User Interface) JDBC Data base Two-Tier Architecture Middle Tier (Business Logic) JDBC Data base Three-Tier Architecture Client (User Interface) JSP / Servlets /EJB HTTP/ RMI/ CORBA HTML/ JavaScri -pt/XML
  • 7. JDBC Driver A JDBC driver implements the interface to a particular database This allows you to develop your program in a database-independent way and connect to a specific database engine by plugging in the appropriate JDBC driver at deployment time There are several kinds of JDBC drivers JDBC-ODBC bridge drivers are useful for small business applications ODBC(Open Database Connectivity) is a technology developed by Microsoft to allow generic access to a DBMS on Windows platform
  • 8. JDBC Driver Types The four structurally different types of JDBC drivers are as follows: Type 1: JDBC-ODBC bridge plus ODBC driver Type 2: Native-API partly Java driver Type 3:JDBC-Net pure Java driver Type 4: Native-protocol pure Java driver
  • 9. Type 1: JDBC-ODBC bridge plus ODBC driver The JDBC-ODBC bridge product provides JDBC access via ODBC drivers. ODBC (Open Database Connectivity) predates JDBC and is widely used to connect to databases in a non-Java environment. ODBC is probably the most widely available programming interface for accessing relational databases.
  • 10. Type 2: Native-API partly Java driver Type 2 drivers use a native API to communicate with a database system. Java Native methods are used to invoke the API functions that perform database operations. A big advantage of Type 2 drivers is that they are generally faster than Type 1 drivers. The primary disadvantages of Type 2 drivers are as follows: Type 2 drivers require native code on the target machine. The Java Native Interface on which they depend is not consistently implemented among different vendors of Java virtual machines.
  • 11. Type 3:JDBC-Net pure Java driver Type 3 drivers translate JDBC calls into a DBMS independent net protocol that is then translated to a DBMS protocol by a server. Advantages of Type 3 drivers are the following: Type 3 drivers do not require any native binary code on the client. Type 3 drivers do not need client installation. Type 3 drivers support several networking options, such as HTTP tunneling. A major drawback of Type 3 drivers is that they can be difficult to set up since the architecture is complicated by the network interface.
  • 12. Type 4: Native-protocol pure Java driver The Type 4 driver is a native protocol, 100- percent Java driver. This allows direct calls from a Java client to a DBMS server. Because the Type 4 driver is written in 100-percent Java, it requires no configuration on the client machine other than telling your application where to find the driver. This allows a direct call from the client machine to the DBMS server. Many of these protocols are proprietary, so these drivers are provided by the database vendors themselves.
  • 13. JDBC Architecture Java application JDBC- Driver manager Native Protocol driver JDBC- Net-driver Native API-driver JDBC-ODBC bridge Client library DB- Middleware ODBC Client library JDBC-API Driver selection is based on the architecture of the application (Two-tier vs Three-tier) and tradeoffs of speed, portability and reliability
  • 14. Steps required to Access DB
  • 15. Driver Manager The java.sql.DriverManager provides basic services for managing JDBC drivers During initialization, the DriverManager attempts to load the driver classes referenced in the "jdbc.drivers" system property. Alternatively, a program can explicitly load JDBC drivers at any time using Class.forName(). This allows a user to customize the JDBC drivers their applications use. A newly loaded driver class should call registerDriver() to make itself known to the DriverManager. Usually, the driver does this internally.
  • 16. ODBC Data Source Administrator You can use ODBC Data Source Administrator to configure your applications so that they can get data from a variety of database management systems. Using Data Sources (ODBC) You can use Data Sources Open Database Connectivity (ODBC) to access data from a variety of database management systems. For example, if you have a program that accesses data in a SQL database, Data Sources (ODBC) will let you use the same program to access data in a Visual FoxPro database. To do this, you must add software components called drivers to your system. Data Sources (ODBC) helps you add and configure these drivers.
  • 17. Loading a Driver import java.sql.* ; Import the Java SQL packages Load the JDBC Driver class SampleJDBC { public static void main(String args[]) { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); /* throws ClassNotFoundException, if the class can’t be located */
  • 18. Connection A Connection object represents a connection with a database. A connection session includes the SQL statements that are executed and the results that are returned over that connection. A single application can have one or more connections with a single database, or it can have connections with many different databases.
  • 19. Opening a connection The standard way to establish a connection with a database is to call the method getConnection() on either a DataSource or a DriverManager. The Driver method connect uses this URL to establish the connection.
  • 20. Connecting to the Database Connection c = DriverManager.getConnection("jdbc:odbc:acc"); /* Connection c = DriverManager.getConnection("jdbc:odbc:ora", "scott", "tiger"); */ /* The DriverManager will select the appropriate driver and setup the DB connection */ Connecting to database
  • 21. SQL Statements Once a connection is established, it is used to pass SQL statements to the database. Since there are no restrictions imposed on the kinds of SQL statements that may be sent to a DBMS using JDBC, the user has a great deal of flexibility to use database-specific statements or even non-SQL statements. The JDBC core API provides these three classes for sending SQL statements to the database:
  • 22. SQL Statements cont… Statement: A Statement object is used for sending simple SQL statements. Statements are created by the method createStatement(). PreparedStatement: A PreparedStatement is a SQL statement that is precompiled and stored in a PreparedStatement object. This object can then be used to execute this statement multiple times. CallableStatement: CallableStatement is used to execute SQL stored procedures. CallableStatements are created by the method prepareCall().
  • 23. Creating a statement Statement s = c.createStatement(); /* A JDBC Statement object has methods that can be used to: - execute SQL queries (SELECT) - execute SQL DML commands (INSERT, UPDATE, DELETE) and DDL commands (CREATE TABLE, ALTER TABLE, DROP TABLE) */ Create a statement
  • 24. Executing SQL Query ResultSet rs=s.executeQuery("select sid, sname, rating from Sailors"); s.executeUpdate("insert into Sailors values (80,'ravi',6, 23)"); Executing a query Inserting a row
  • 25. Processing Resultset while(rs.next()) { System.out.println("n"+rs.getInt(1) + "t" + rs.getString(2) + "t" + rs.getInt(3)); } Processing Resultset /* A result set can be viewed as a table of data containing rows as a result of a query */
  • 26. Retrieving Data Individual columns values are read using one of the getXXX() methods. (e.g. getString(), getInt(), getFloat(), getDate(), etc.) There are two versions of each getXXX() method: • one that takes the case-insensitive String name of the column • one that takes an SQL-style column index column numbers begin at 1 ex: s = rs.getString(1); s = rs.getString(“sname”);
  • 27. ResultSet MetaData ResultSetMetaData rm=rs.getMetaData(); /* Metadata is data about data. The resultset metadata contains information about the columns in the result set */ for(int i=1;i<=rm.getColumnCount();i++) System.out.print(rm.getColumnName(i)+ "t"); Retrieving Column Info No.of Columns & Names of Columns
  • 28. Releasing Resources rs.close(); s.close(); c.close(); Releasing Resources /* All methods of Connection, Statement, ResultSet & other JDBC API may throw SQLException */
  • 29. Summary Load Driver Connecting to the database Create Statement Execute Statement Process Resultset More results ? Release Resources no yes
  • 30. Prepared Statements If executing similar SQL statements multiple times, using “prepared statement” may be more efficient Statement is created in standard form that is sent to the database for compilation before actually being used Each time you use it, you simply replace some of the marked parameters using the setXxx methods
  • 31. Conclusion Through JDBC we can create very good Java applications which need to access databases JDBC is used with JSP/EJB to create web applications

Editor's Notes

  1. 3
  2. 7