SlideShare a Scribd company logo
T.DEEPIKA(INFO-TECH)
NADAR SARASWATHI COLLEGE OF ARTS AND
SCIENCE
JDBC - Java Database Connectivity
The objectives of this chapter are:
To describe the architecture of JDBC
To outline the classes in the java.sql package
To understand the use of JDBC
What is JDBC?
JDBC provides Java applications with access to most
database systems via SQL
The architecture and API closely resemble Microsoft's
ODBC
JDBC 1.0 was originally introduced into Java 1.1
JDBC 2.0 was added to Java 1.2
JDBC is based on SQL-92
JDBC classes are contained within the java.sql package
There are few classes
There are several interfaces
Database Connectivity History
Before APIs like JDBC and ODBC, database
connectivity was tedious
Each database vendor provided a function library for accessing
their database
The connectivity library was proprietary.
If the database vendor changed for the application, the data access
portions had to be rewritten
If the application was poorly structured, rewriting its data access
might involve rewriting the majority of the application
The costs incurred generally meant that application developers
were stuck with a particular database product for a given
application
JDBC Architecture
With JDBC, the application programmer uses the JDBC API
The developer never uses any proprietary APIs
• Any proprietary APIs are implemented by a JDBC driver
• There are 4 types of JDBC Drivers
JDBC Drivers
There are 4 types of JDBC Drivers
Type 1 - JDBC-ODBC Bridge
Type 2 - JDBC-Native Bridge
Type 3 - JDBC-Net Bridge
Type 4 - Direct JDBC Driver
Type 1 only runs on platforms where ODBC is available
ODBC must be configured separately
Type 2 Drivers map between a proprietary Database API and
the JDBC API
Type 3 Drivers are used with middleware products
Type 4 Drivers are written in Java
In most cases, type 4 drivers are preferred
JDBC Classes
DriverManager
Manages JDBC Drivers
Used to Obtain a connection to a Database
• Types
Defines constants which identify SQL types
Date
Used to Map between java.util.Date and the SQL DATE type
• Time
Used to Map between java.util.Date and the SQL TIME type
TimeStamp
Used to Map between java.util.Date and the SQL TIMESTAMP type
JDBC Interfaces
Driver
All JDBC Drivers must implement the Driver interface. Used to
obtain a connection to a specific database type
• Connection
Represents a connection to a specific database
Used for creating statements
Used for managing database transactions
Used for accessing stored procedures
Used for creating callable statements
Statement
Used for executing SQL statements against the database
JDBC Interfaces
ResultSet
Represents the result of an SQL statement
Provides methods for navigating through the resulting data
• PreparedStatement
Similar to a stored procedure
An SQL statement (which can contain parameters) is compiled and stored in
the database
CallableStatement
Used for executing stored procedures
DatabaseMetaData
Provides access to a database's system catalogue
ResultSetMetaData
Provides information about the data contained within a ResultSet
Using JDBC
To execute a statement against a database, the following
flow is observed
Load the driver (Only performed once)
Obtain a Connection to the database (Save for later use)
Obtain a Statement object from the Connection
Use the Statement object to execute SQL. Updates, inserts and
deletes return Boolean. Selects return a ResultSet
Navigate ResultSet, using data as required
Close ResultSet
Close Statement
• Do NOT close the connection
The same connection object can be used to create further statements
A Connection may only have one active Statement at a time. Do not
forget to close the statement when it is no longer needed.
Close the connection when you no longer need to access the database
Loading Drivers
Even a good API can have problems
Loading drivers fits into this category
The DriverManager is a singleton
Each JDBC Driver is also a singleton
When a JDBC Driver class is loaded, it must create an instance of
itself and register that instance with the JDBC DriverManager
How does one load a "class" into the Virtual machine?
Use the static method Class.forName()
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connecting to a Database
Once a Driver is loaded, a connection can be made to the database
The connection is defined by URL
The URL has the following form:
jdbc:driver:databasename
• Examples:
jdbc:odbc:MyOdbcDatabase
jdbc:postgres:WebsiteDatabase
jdbc:oracle:CustomerInfo
A connection is obtained in the following manner:
Connection aConnection = DriverManager.getConnection("jdbc:odbc:myDatabase");
• Overloaded versions of the getConnection method allow the
specification of a username and password for authentication with the
database.
Using a Connection
The Connection interface defines many methods for
managing and using a connection to the database
public Statement createStatement()
public PreparedStatement prepareStatement(String sql)
public void setAutoCommit(boolean)
public void commit()
public void rollback()
public void close()
• The most commonly used method is createStatement()
When an SQL statement is to be issued against the database, a
Statement object must be created through the Connection
Using a Statement
The Statement interface defines two methods for
executing SQL against the database
public ResultSet executeQuery(String sql)
public int executeUpdate(String sql)
• executeQuery returns a ResultSet
• All rows and columns which match the query are contained within the
ResultSet
• The developer navigates through the ResultSet and uses the data as
required.
• executeUpdate returns the number of rows changed by
the update statement
This is used for insert statements, update statements and delete
statements
Using a ResultSet
The ResultSet interface defines many navigation methods
public boolean first()
public boolean last()
public boolean next()
public boolean previous()
The ResultSet interface also defines data access methods
public int getInt(int columnNumber) -- Note: Columns are numbered
public int getInt(String columnName) -- from 1 (not 0)
public long getLong(int columnNumber)
public long getLong(String columnName)
public String getString(int columnNumber)
public String getString(String columnName)
There are MANY more methods. Check the API
documentation for a complete list
SQL Types/Java Types Mapping
SQL Type Java Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.Math.BigDecimal
DECIMAL java.Math.BigDecimal
BIT boolean
TINYINT int
SMALLINT int
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Example Code:
Connection aConnection;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException x)
{
System.out.println("Cannot find driver class. Check CLASSPATH");
return;
}
try
{
aConnection = DriverManager.getConnection("jdbc:odbc:MyDatabase",
"Username", "Password");
}
catch(SQLException x)
{
System.out.println("Exception connecting to database:" + x);
return;
}
Example Code (continued):
try
{
Statement aStmt = aConnection.createStatement();
StringBuffer sb = new StringBuffer("SELECT Employee_id, Employee_Name");
sb.append(" FROM Employee WHERE EmployeeId>100");
ResultSet rs = aStmt.executeQuery(sb.toString());
while(rs.next())
{
int employeeId = rs.getInt(1);
String employeeName = rs.getString(2);
System.out.println("Id:" + employeeId + "nName:" + employeeName);
}
rs.close();
aStmt.close();
}
catch(SQLException x)
{
System.out.println("Exception while executing query:" + x);
}
THANKYOU

More Related Content

What's hot

Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
suraj pandey
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginersAmbarish Rai
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
Waheed Warraich
 
Jdbc
JdbcJdbc
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
Rohit Jain
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
Mazenetsolution
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
Pallepati Vasavi
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
Ravinder Singh Karki
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
JDBC
JDBCJDBC
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database Connectivity
Gary Yeh
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
Nuha Noor
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
Muthukumaran Subramanian
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
Ankit Desai
 

What's hot (20)

Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc document
jdbc documentjdbc document
jdbc document
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
JDBC
JDBCJDBC
JDBC
 
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database Connectivity
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
 

Similar to Jdbc

Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
arikazukito
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
saturo3011
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
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
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
Sourabrata Mukherjee
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
Luzan Baral
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
Sunita Milind Dol
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
java.pptx
java.pptxjava.pptx
java.pptx
bfgd1
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
Hemo Chella
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
Mythili Shankar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
Kumar
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 

Similar to Jdbc (20)

Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
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
 
Jdbc
JdbcJdbc
Jdbc
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
JDBC
JDBCJDBC
JDBC
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
java.pptx
java.pptxjava.pptx
java.pptx
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
jdbc
jdbcjdbc
jdbc
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 

More from DeepikaT13

Mobile computing
Mobile computingMobile computing
Mobile computing
DeepikaT13
 
Image processing
Image processingImage processing
Image processing
DeepikaT13
 
aloha
alohaaloha
aloha
DeepikaT13
 
Spatial filtering
Spatial filteringSpatial filtering
Spatial filtering
DeepikaT13
 
Exceptions
ExceptionsExceptions
Exceptions
DeepikaT13
 
Hive architecture
Hive  architectureHive  architecture
Hive architecture
DeepikaT13
 
Rdbms
RdbmsRdbms
Rdbms
DeepikaT13
 
Sotware engineering
Sotware engineeringSotware engineering
Sotware engineering
DeepikaT13
 
Data mining
Data miningData mining
Data mining
DeepikaT13
 
Computer network
Computer networkComputer network
Computer network
DeepikaT13
 
Storage management in operating system
Storage management in operating systemStorage management in operating system
Storage management in operating system
DeepikaT13
 
Data mining
Data miningData mining
Data mining
DeepikaT13
 
Neural network
Neural networkNeural network
Neural network
DeepikaT13
 
memory reference instruction
memory reference instructionmemory reference instruction
memory reference instruction
DeepikaT13
 
breadth first search
breadth first searchbreadth first search
breadth first search
DeepikaT13
 
constructors
constructorsconstructors
constructors
DeepikaT13
 
Disjoint set
Disjoint setDisjoint set
Disjoint set
DeepikaT13
 
Destructors
DestructorsDestructors
Destructors
DeepikaT13
 
Crisp set
Crisp setCrisp set
Crisp set
DeepikaT13
 
Computer registers
Computer registersComputer registers
Computer registers
DeepikaT13
 

More from DeepikaT13 (20)

Mobile computing
Mobile computingMobile computing
Mobile computing
 
Image processing
Image processingImage processing
Image processing
 
aloha
alohaaloha
aloha
 
Spatial filtering
Spatial filteringSpatial filtering
Spatial filtering
 
Exceptions
ExceptionsExceptions
Exceptions
 
Hive architecture
Hive  architectureHive  architecture
Hive architecture
 
Rdbms
RdbmsRdbms
Rdbms
 
Sotware engineering
Sotware engineeringSotware engineering
Sotware engineering
 
Data mining
Data miningData mining
Data mining
 
Computer network
Computer networkComputer network
Computer network
 
Storage management in operating system
Storage management in operating systemStorage management in operating system
Storage management in operating system
 
Data mining
Data miningData mining
Data mining
 
Neural network
Neural networkNeural network
Neural network
 
memory reference instruction
memory reference instructionmemory reference instruction
memory reference instruction
 
breadth first search
breadth first searchbreadth first search
breadth first search
 
constructors
constructorsconstructors
constructors
 
Disjoint set
Disjoint setDisjoint set
Disjoint set
 
Destructors
DestructorsDestructors
Destructors
 
Crisp set
Crisp setCrisp set
Crisp set
 
Computer registers
Computer registersComputer registers
Computer registers
 

Recently uploaded

Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 

Recently uploaded (20)

Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 

Jdbc

  • 2. JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package To understand the use of JDBC
  • 3. What is JDBC? JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble Microsoft's ODBC JDBC 1.0 was originally introduced into Java 1.1 JDBC 2.0 was added to Java 1.2 JDBC is based on SQL-92 JDBC classes are contained within the java.sql package There are few classes There are several interfaces
  • 4. Database Connectivity History Before APIs like JDBC and ODBC, database connectivity was tedious Each database vendor provided a function library for accessing their database The connectivity library was proprietary. If the database vendor changed for the application, the data access portions had to be rewritten If the application was poorly structured, rewriting its data access might involve rewriting the majority of the application The costs incurred generally meant that application developers were stuck with a particular database product for a given application
  • 5. JDBC Architecture With JDBC, the application programmer uses the JDBC API The developer never uses any proprietary APIs • Any proprietary APIs are implemented by a JDBC driver • There are 4 types of JDBC Drivers
  • 6. JDBC Drivers There are 4 types of JDBC Drivers Type 1 - JDBC-ODBC Bridge Type 2 - JDBC-Native Bridge Type 3 - JDBC-Net Bridge Type 4 - Direct JDBC Driver Type 1 only runs on platforms where ODBC is available ODBC must be configured separately Type 2 Drivers map between a proprietary Database API and the JDBC API Type 3 Drivers are used with middleware products Type 4 Drivers are written in Java In most cases, type 4 drivers are preferred
  • 7. JDBC Classes DriverManager Manages JDBC Drivers Used to Obtain a connection to a Database • Types Defines constants which identify SQL types Date Used to Map between java.util.Date and the SQL DATE type • Time Used to Map between java.util.Date and the SQL TIME type TimeStamp Used to Map between java.util.Date and the SQL TIMESTAMP type
  • 8. JDBC Interfaces Driver All JDBC Drivers must implement the Driver interface. Used to obtain a connection to a specific database type • Connection Represents a connection to a specific database Used for creating statements Used for managing database transactions Used for accessing stored procedures Used for creating callable statements Statement Used for executing SQL statements against the database
  • 9. JDBC Interfaces ResultSet Represents the result of an SQL statement Provides methods for navigating through the resulting data • PreparedStatement Similar to a stored procedure An SQL statement (which can contain parameters) is compiled and stored in the database CallableStatement Used for executing stored procedures DatabaseMetaData Provides access to a database's system catalogue ResultSetMetaData Provides information about the data contained within a ResultSet
  • 10. Using JDBC To execute a statement against a database, the following flow is observed Load the driver (Only performed once) Obtain a Connection to the database (Save for later use) Obtain a Statement object from the Connection Use the Statement object to execute SQL. Updates, inserts and deletes return Boolean. Selects return a ResultSet Navigate ResultSet, using data as required Close ResultSet Close Statement • Do NOT close the connection The same connection object can be used to create further statements A Connection may only have one active Statement at a time. Do not forget to close the statement when it is no longer needed. Close the connection when you no longer need to access the database
  • 11. Loading Drivers Even a good API can have problems Loading drivers fits into this category The DriverManager is a singleton Each JDBC Driver is also a singleton When a JDBC Driver class is loaded, it must create an instance of itself and register that instance with the JDBC DriverManager How does one load a "class" into the Virtual machine? Use the static method Class.forName() Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  • 12. Connecting to a Database Once a Driver is loaded, a connection can be made to the database The connection is defined by URL The URL has the following form: jdbc:driver:databasename • Examples: jdbc:odbc:MyOdbcDatabase jdbc:postgres:WebsiteDatabase jdbc:oracle:CustomerInfo A connection is obtained in the following manner: Connection aConnection = DriverManager.getConnection("jdbc:odbc:myDatabase"); • Overloaded versions of the getConnection method allow the specification of a username and password for authentication with the database.
  • 13. Using a Connection The Connection interface defines many methods for managing and using a connection to the database public Statement createStatement() public PreparedStatement prepareStatement(String sql) public void setAutoCommit(boolean) public void commit() public void rollback() public void close() • The most commonly used method is createStatement() When an SQL statement is to be issued against the database, a Statement object must be created through the Connection
  • 14. Using a Statement The Statement interface defines two methods for executing SQL against the database public ResultSet executeQuery(String sql) public int executeUpdate(String sql) • executeQuery returns a ResultSet • All rows and columns which match the query are contained within the ResultSet • The developer navigates through the ResultSet and uses the data as required. • executeUpdate returns the number of rows changed by the update statement This is used for insert statements, update statements and delete statements
  • 15. Using a ResultSet The ResultSet interface defines many navigation methods public boolean first() public boolean last() public boolean next() public boolean previous() The ResultSet interface also defines data access methods public int getInt(int columnNumber) -- Note: Columns are numbered public int getInt(String columnName) -- from 1 (not 0) public long getLong(int columnNumber) public long getLong(String columnName) public String getString(int columnNumber) public String getString(String columnName) There are MANY more methods. Check the API documentation for a complete list
  • 16. SQL Types/Java Types Mapping SQL Type Java Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.Math.BigDecimal DECIMAL java.Math.BigDecimal BIT boolean TINYINT int SMALLINT int INTEGER int BIGINT long REAL float FLOAT double DOUBLE double BINARY byte[] VARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp
  • 17. Example Code: Connection aConnection; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException x) { System.out.println("Cannot find driver class. Check CLASSPATH"); return; } try { aConnection = DriverManager.getConnection("jdbc:odbc:MyDatabase", "Username", "Password"); } catch(SQLException x) { System.out.println("Exception connecting to database:" + x); return; }
  • 18. Example Code (continued): try { Statement aStmt = aConnection.createStatement(); StringBuffer sb = new StringBuffer("SELECT Employee_id, Employee_Name"); sb.append(" FROM Employee WHERE EmployeeId>100"); ResultSet rs = aStmt.executeQuery(sb.toString()); while(rs.next()) { int employeeId = rs.getInt(1); String employeeName = rs.getString(2); System.out.println("Id:" + employeeId + "nName:" + employeeName); } rs.close(); aStmt.close(); } catch(SQLException x) { System.out.println("Exception while executing query:" + x); }