SlideShare a Scribd company logo
1 of 24
JDBC
Java Database Connectivity
Rohit Jain
DTU
B.Tech, Software Engineering
What is JDBC?
 JDBC API allows Java programs to
connect to DBs
 Provides cross-vendor connectivity and
data access across relational databases
from different vendors
 Classes and interfaces allow users to
access the database in a standard way
 The JVM uses the JDBC driver to
translate generalized JDBC calls into
vendor specific database calls
What Does JDBC Do ?
JDBC makes it possible to do three things:
Establish a connection with a database
Send SQL statements
Process the results.
JDBC Classes for DB
Connection
 java.sql.Driver
◦ Unless creating custom JDBC implementation, never
have to deal with it. It gives JDBC a launching point
for DB connectivity by responding to
DriverManager connection requests
 java.sql.DriverManager
◦ Maintains a list of Driver implementations and
presents an application with one that matches a
requested URL.
◦ getConnection(url, uid, password)
◦ getDrivers(), registerDriver()
 java.sql.Connection
◦ Represents a single logical DB connection; used for
sending SQL statements
JDBC Drivers
 JDBC-ODBC bridge
 Part Java, Part Native Driver
 Intermediate DAccess Server
 Pure Java Drivers
Driver Manager
 The purpose of the
java.sql.DriverManger class in JDBC is
to provide a common access layer on top
of different database drivers used in an
application
 DriverManager requires that each driver
required by the application must be
registered before use
 Load the database driver using
ClassLoader
 Class.forName(“oracle.jdbc.driver.Oracle
Driver”);
Registering a JDBC Driver
 Driver must be registered before it is
used.
 Drivers can be registered in three
ways.
Most Common Approach is
 To use Java’s Class.forName()
 Dynamically loads the driver’s class
file into memory
 Preferable because
It allows driver registration
configurable and portable.
 The second approach you can use to
register a driver is to use the static
DriverManager.registerDriver( )
method.
 Use the registerDriver( ) method if
you
are using a non-JDK compliant JVM.
For example:
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver( ));
 The third approach is to use a
combination of Class.forName( ) to
dynamically load the Oracle driver and
then the driver classes' getInstance( )
method to work around noncompliant
JVMs.
 For example:
Class.forName("oracle.jdbc.driver.Oracle
Driver").newInstance();
Basic steps to use
a database in Java
 Establish a connection
 Create JDBC Statements
 Execute SQL Statements
 GET ResultSet
 Close connections
1. Establish a connection
 import java.sql.*;
 Load the vendor specific driver
◦ Class.forName("oracle.jdbc.driver.OracleDriver");
 What do you think this statement does, and how?
 Dynamically loads a driver class, for Oracle database
 Make the connection
◦ Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@oracle-prod:1521:OPROD", username,
passwd);
 What do you think this statement does?
 Establishes connection to database by obtaining
a Connection object
2. Create JDBC statement(s)
 Statement stmt = con.createStatement()
;
 Creates a Statement object for
sending SQL statements to the
database
3.Executing SQL Statements
 String createStudent = "Create table
Student " +
"(SSN Integer not null, Name
VARCHAR(32), " + "Marks Integer)";
stmt.executeUpdate(createStudent);
//What does this statement do?
 String insertStudent = "Insert into
Student values“ +
"(123456789,abc,100)";
stmt.executeUpdate(insertStudent);
Execute Statements
 This uses executeUpdate because the
SQL statement contained in
createTableCoffees is a data definition
language ( DDL ) statement
 DDL statements are executed with
executeUpdate
– Create a table
– Alter a table
– Drop a table
 executeUpdate is also used to execute
SQL statements that update a table
Execute Statements
 executeUpdate is used far more often
to update tables than to create them–
We create a table once but update it
many times
 The method used most often for
executing SQL statements is
executeQuery
 executeQuery is used to execute
SELECT statements – SELECT
statements are the most common SQL
statements
Entering Data to a Table
 Statement stmt = con.createStatement();
 stmt.executeUpdate ( "INSERT INTO COFFEES
" +
"VALUES ('Colombian', 101, 7.99, 0, 0)");
 stmt.executeUpdate ("INSERT INTO COFFEES "
+
"VALUES ('French_Roast', 49, 8.99, 0, 0)");
 stmt.executeUpdate ("INSERT INTO COFFEES "
+
"VALUES ('Espresso', 150, 9.99, 0, 0)");
 stmt.executeUpdate ("INSERT INTO COFFEES "
+
"VALUES ('Colombian Decaf' 101 8 99 0 0)");
 stmt.executeUpdate ("INSERT INTO COFFEES "
+
Batch Update
 What is batch update?
- Send multiple update statement in a
single request to the database
 Why batch update?
-Better performance
 How do we perform batch update?
-Statement.addBatch (sqlString);
- Statement.executeBatch();
4.Get ResultSet
String queryStudent = "select * from Student";
ResultSet rs =
Stmt.executeQuery(queryStudent);
//What does this statement do?
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
5. Close connection
 stmt.close();
 con.close();
Sample Program
import java.sql.*;
class TestThinApp {
public static void main (String args[])
throws ClassNotFoundException,
SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver
");
// or you can use:
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","scott","ti
Statement stmt = conn.createStatement( );
ResultSet rset = stmt.executeQuery(
"select 'Hello Thin driver tester '||USER||'!'
result from dual");
while(rset.next( ))
System.out.println(rset.getString(1));
rset.close( );
stmt.close( );
conn.close( );
}
}
SUMMARY
 JDBC makes it very easy to connect
to DBMS and to manipulate the data
in it.
 You have to install the oracle driver in
order to make the connection.
 It is crucial to setup PATH and
CLASSPATH properly
Thanks…..

More Related Content

What's hot

What's hot (20)

Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Json
JsonJson
Json
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Java swing
Java swingJava swing
Java swing
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 

Viewers also liked

JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
How much security is enough?
How much security is enough?How much security is enough?
How much security is enough?Sherry Jones
 
SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"
SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"
SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"SOLOMOTO_RU
 
Veiktais darbs nedēļas laikā
Veiktais darbs nedēļas laikāVeiktais darbs nedēļas laikā
Veiktais darbs nedēļas laikārlycky
 
Reference Corey Jay
Reference Corey JayReference Corey Jay
Reference Corey JayCorey Jay
 
Promes dan-pemetaan-smtr-1
Promes dan-pemetaan-smtr-1Promes dan-pemetaan-smtr-1
Promes dan-pemetaan-smtr-1sifatulfalah3120
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)Craig Dickson
 
Creating Teaching Videos in the Studio
Creating Teaching Videos in the StudioCreating Teaching Videos in the Studio
Creating Teaching Videos in the StudioKristen Sosulski
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Digitization in supply chain management
Digitization in supply chain managementDigitization in supply chain management
Digitization in supply chain managementHae-Goo Song
 

Viewers also liked (20)

Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Power final entre iguals 18 desembre
Power final entre iguals 18 desembre Power final entre iguals 18 desembre
Power final entre iguals 18 desembre
 
Relco Brochure Mail
Relco Brochure MailRelco Brochure Mail
Relco Brochure Mail
 
Rpp ix 2
Rpp ix 2Rpp ix 2
Rpp ix 2
 
How much security is enough?
How much security is enough?How much security is enough?
How much security is enough?
 
SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"
SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"
SOLOMOTO_Продвижение через социальную сеть "ВКонтакте"
 
Veiktais darbs nedēļas laikā
Veiktais darbs nedēļas laikāVeiktais darbs nedēļas laikā
Veiktais darbs nedēļas laikā
 
Reference Corey Jay
Reference Corey JayReference Corey Jay
Reference Corey Jay
 
ABC
ABCABC
ABC
 
Promes dan-pemetaan-smtr-1
Promes dan-pemetaan-smtr-1Promes dan-pemetaan-smtr-1
Promes dan-pemetaan-smtr-1
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Creating Teaching Videos in the Studio
Creating Teaching Videos in the StudioCreating Teaching Videos in the Studio
Creating Teaching Videos in the Studio
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Digitization in supply chain management
Digitization in supply chain managementDigitization in supply chain management
Digitization in supply chain management
 

Similar to JDBC ppt (20)

Jdbc
JdbcJdbc
Jdbc
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Select query in JDBC
Select query in JDBCSelect query in JDBC
Select query in JDBC
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
Jdbc
JdbcJdbc
Jdbc
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
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
 
Jdbc
JdbcJdbc
Jdbc
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

JDBC ppt

  • 1. JDBC Java Database Connectivity Rohit Jain DTU B.Tech, Software Engineering
  • 2. What is JDBC?  JDBC API allows Java programs to connect to DBs  Provides cross-vendor connectivity and data access across relational databases from different vendors  Classes and interfaces allow users to access the database in a standard way  The JVM uses the JDBC driver to translate generalized JDBC calls into vendor specific database calls
  • 3. What Does JDBC Do ? JDBC makes it possible to do three things: Establish a connection with a database Send SQL statements Process the results.
  • 4. JDBC Classes for DB Connection  java.sql.Driver ◦ Unless creating custom JDBC implementation, never have to deal with it. It gives JDBC a launching point for DB connectivity by responding to DriverManager connection requests  java.sql.DriverManager ◦ Maintains a list of Driver implementations and presents an application with one that matches a requested URL. ◦ getConnection(url, uid, password) ◦ getDrivers(), registerDriver()  java.sql.Connection ◦ Represents a single logical DB connection; used for sending SQL statements
  • 5. JDBC Drivers  JDBC-ODBC bridge  Part Java, Part Native Driver  Intermediate DAccess Server  Pure Java Drivers
  • 6. Driver Manager  The purpose of the java.sql.DriverManger class in JDBC is to provide a common access layer on top of different database drivers used in an application  DriverManager requires that each driver required by the application must be registered before use  Load the database driver using ClassLoader  Class.forName(“oracle.jdbc.driver.Oracle Driver”);
  • 7. Registering a JDBC Driver  Driver must be registered before it is used.  Drivers can be registered in three ways.
  • 8. Most Common Approach is  To use Java’s Class.forName()  Dynamically loads the driver’s class file into memory  Preferable because It allows driver registration configurable and portable.
  • 9.  The second approach you can use to register a driver is to use the static DriverManager.registerDriver( ) method.  Use the registerDriver( ) method if you are using a non-JDK compliant JVM. For example: DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver( ));
  • 10.  The third approach is to use a combination of Class.forName( ) to dynamically load the Oracle driver and then the driver classes' getInstance( ) method to work around noncompliant JVMs.  For example: Class.forName("oracle.jdbc.driver.Oracle Driver").newInstance();
  • 11. Basic steps to use a database in Java  Establish a connection  Create JDBC Statements  Execute SQL Statements  GET ResultSet  Close connections
  • 12. 1. Establish a connection  import java.sql.*;  Load the vendor specific driver ◦ Class.forName("oracle.jdbc.driver.OracleDriver");  What do you think this statement does, and how?  Dynamically loads a driver class, for Oracle database  Make the connection ◦ Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@oracle-prod:1521:OPROD", username, passwd);  What do you think this statement does?  Establishes connection to database by obtaining a Connection object
  • 13. 2. Create JDBC statement(s)  Statement stmt = con.createStatement() ;  Creates a Statement object for sending SQL statements to the database
  • 14. 3.Executing SQL Statements  String createStudent = "Create table Student " + "(SSN Integer not null, Name VARCHAR(32), " + "Marks Integer)"; stmt.executeUpdate(createStudent); //What does this statement do?  String insertStudent = "Insert into Student values“ + "(123456789,abc,100)"; stmt.executeUpdate(insertStudent);
  • 15. Execute Statements  This uses executeUpdate because the SQL statement contained in createTableCoffees is a data definition language ( DDL ) statement  DDL statements are executed with executeUpdate – Create a table – Alter a table – Drop a table  executeUpdate is also used to execute SQL statements that update a table
  • 16. Execute Statements  executeUpdate is used far more often to update tables than to create them– We create a table once but update it many times  The method used most often for executing SQL statements is executeQuery  executeQuery is used to execute SELECT statements – SELECT statements are the most common SQL statements
  • 17. Entering Data to a Table  Statement stmt = con.createStatement();  stmt.executeUpdate ( "INSERT INTO COFFEES " + "VALUES ('Colombian', 101, 7.99, 0, 0)");  stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES ('French_Roast', 49, 8.99, 0, 0)");  stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES ('Espresso', 150, 9.99, 0, 0)");  stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES ('Colombian Decaf' 101 8 99 0 0)");  stmt.executeUpdate ("INSERT INTO COFFEES " +
  • 18. Batch Update  What is batch update? - Send multiple update statement in a single request to the database  Why batch update? -Better performance  How do we perform batch update? -Statement.addBatch (sqlString); - Statement.executeBatch();
  • 19. 4.Get ResultSet String queryStudent = "select * from Student"; ResultSet rs = Stmt.executeQuery(queryStudent); //What does this statement do? while (rs.next()) { int ssn = rs.getInt("SSN"); String name = rs.getString("NAME"); int marks = rs.getInt("MARKS"); }
  • 20. 5. Close connection  stmt.close();  con.close();
  • 21. Sample Program import java.sql.*; class TestThinApp { public static void main (String args[]) throws ClassNotFoundException, SQLException { Class.forName("oracle.jdbc.driver.OracleDriver "); // or you can use: DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","scott","ti
  • 22. Statement stmt = conn.createStatement( ); ResultSet rset = stmt.executeQuery( "select 'Hello Thin driver tester '||USER||'!' result from dual"); while(rset.next( )) System.out.println(rset.getString(1)); rset.close( ); stmt.close( ); conn.close( ); } }
  • 23. SUMMARY  JDBC makes it very easy to connect to DBMS and to manipulate the data in it.  You have to install the oracle driver in order to make the connection.  It is crucial to setup PATH and CLASSPATH properly