SlideShare una empresa de Scribd logo
1 de 25
ADVANCE JAVA
ADVANCE JAVA
Author Profile
 Ankit Desai
 Ph.D. Scholar, IET, Ahmedabad University
 Education: M. Tech. (C.E.), B. E. (I. T.)
 Experience: 8 years (Academic and Research)
 Research Interest: IoT, Big Data Analytics, Machine
Learning, Data Mining, Algorithms.
Classified e-Material 2
ADVANCE JAVA
Classified e-Material
Java Database Connectivity
JDBC Basics
Application
ADVANCE JAVA
Classified e-Material
Agenda
 What is JDBC?
 JDBC API
 JDBC Driver
 Database URL
 Step By Step Usage of JDBC API
 Load DB-specific JDBC driver
 Get a Connection object
 Get a Statement object
 Execute queries and/or updates
 Read results
 Read Meta-data (optional step)
 Close Statement and Connection objects
ADVANCE JAVA
What is JDBC?
 Java Database
Connectivity (JDBC) is a
programming framework
to get data from
 databases
 spreadsheets
 flat files
 Standard Java API for
accessing relational
database
 Hides database specific
details from application
Classified e-Material
DBMS
Java Application
JDBC
Client Machine
DBMS.propritary protocol
Database Server
ADVANCE JAVA
Four types of JDBC Drivers
Classified e-Material
JDBC
Type I
“Bridge”
Type II
“Native”
Type III
“Middleware”
Type IV
“Pure”
ODBC
ODBC
Driver
CLI (.lib)
Middleware
Server
ADVANCE JAVA
Classified e-Material
JDBC API
 Defines a set of Java Interfaces, which are
implemented by vendor-specific JDBC Drivers
 Applications use this set of Java interfaces for
performing database operations
JDBC API Layers
Java Application JDBC API
JDBC Manager JDBC Driver API
JDBC NetDriver
JDBC.ODBC
Bridge
ODBC
Driver
Driver 1 Driver 2
ADVANCE JAVA
Classified e-Material
JDBC API
 Majority of JDBC API is located in java.sql package
 DriverManager, Connection, ResultSet,
DatabaseMetaData, ResultSetMetaData,
PreparedStatement, CallableStatement and Types
 Other advanced functionality exists in the
javax.sql package
 DataSource
ADVANCE JAVA
JDBC Class Usage
Classified e-Material
DriverManager
Driver
Connection
Statement
ResultSet
ADVANCE JAVA
Classified e-Material
JDBC Driver
 Database specific
implementation of JDBC
interfaces
 Every database server
has corresponding JDBC
driver(s)
 You can see the list of
available drivers from
 http://industry.java.sun.com/products/jdbc/drivers
ADVANCE JAVA
Classified e-Material
Database URL
 Used to make a connection to the database
 Can contain server, port, protocol etc…
 jdbc:subprotocol_name:driver_dependant_databasename
 Oracle thin driver
 Jdbc:oracle:thin:@machinename:1521:dbname
 Derby
 jdbc:derby://localhost:1527/sample
 Pointbase
 jdbc:pointbase:server://localhost/sample
ADVANCE JAVA
Classified e-Material
Agenda
 What is JDBC?
 Step By Step Usage of JDBC API
ADVANCE JAVA
Classified e-Material
Steps of Using JDBC
 1.Load DB-specific JDBC driver
 2.Get a Connection object
 3.Get a Statement object
 4.Execute queries and/or updates
 5.Read results
 6.Read Meta-data (optional step)
 7.Close Statement and Connection objects
ADVANCE JAVA
Classified e-Material
1. Load DB-Specific Database Driver
 To manually load the database driver and register it
with the DriverManager, load its class file
 Class.forName(<database-driver>)
try {
// This loads an instance of the Pointbase DB Driver.
// The driver has to be in the classpath.
Class.forName("org.apache.derby.jdbc.ClientDriver")
;
}catch (ClassNotFoundException cnfe){
System.out.println("" + cnfe);
}
Static Method of ClassClass Name
Database Driver String
ADVANCE JAVA
Classified e-Material
2. Get a Connection Object
 DriverManager class is responsible for selecting the
database and and creating the database connection
 Using DataSource is a prefered means of getting a
conection object
 Create the database connection as follows:
try {
Connection connection =
DriverManager.getConnection("jdbc:derby://localhost
:1527/sample", “app"," app ");
} catch(SQLException sqle) {
System.out.println("" + sqle);
}
Create the object of Connection Class
ADVANCE JAVA
Classified e-Material
DriverManager & Connection
 java.sql.DriverManager
 getConnection(String url, String user, String
password) throws SQLException
 java.sql.Connection
 Statement createStatement() throws SQLException
 void close() throws SQLException
 void setAutoCommit(boolean b) throws SQLException
 void commit() throws SQLException
 void rollback() throws SQLException
ADVANCE JAVA
Classified e-Material
3. Get a Statement Object
 Create a Statement Object from Connection object
 java.sql.Statement
 ResultSet executeQuery(string sql)
 int executeUpdate(String sql)
 Example:
 Statement statement = connection.createStatement();
 The same Statement object can be used for many,
unrelated queries
Create Statement Object
ADVANCE JAVA
Classified e-Material
4. Executing Query or Update
 From the Statement object, the 2 most used
commands are
 (a) QUERY (SELECT)
 ResultSet rs = statement.executeQuery("select *
from customer_tbl");
 (b) ACTION COMMAND (UPDATE/DELETE)
 int iReturnValue = statement.executeUpdate("update
manufacture_tbl set name = ‘IBM' where mfr_num =
19985678");
Execute select query
Execute update query
ADVANCE JAVA
Classified e-Material
Steps of Using JDBC
 1.Load DB-specific JDBC driver
 2.Get a Connection object
 3.Get a Statement object
 4.Execute queries and/or updates
 5.Read results
 6.Read Meta-data (optional step)
 7.Close Statement and Connection objects
ADVANCE JAVA
Classified e-Material
5. Reading Results
 Loop through ResultSet retrieving information
 java.sql.ResultSet
 boolean next()
 xxx getXxx(int columnNumber)
 xxx getXxx(String columnName)
 void close()
 The iterator is initialized to a position before the first
row
 You must call next() once to move it to the first row
ADVANCE JAVA
Classified e-Material
5. Reading Results (Continued)
 Once you have the ResultSet, you can easily
retrieve the data by looping through it
while (rs.next()){
// Wrong this will generate an error
String value0 = rs.getString(0);
// Correct!
String value1 = rs.getString(1);
int value2 = rs.getInt(2);
int value3 = rs.getInt(“ADDR_LN1");
}
Move to the next touple while end
Index starts from 1
ADVANCE JAVA
Classified e-Material
5. Reading Results (Continued)
 When retrieving data from the ResultSet, use the
appropriate getXXX() method
 getString()
 getInt()
 getDouble()
 getObject()
 There is an appropriate getXXX method of each
java.sql.Types datatype
ADVANCE JAVA
Classified e-Material
6. Read ResultSet MetaData and DatabaseMetaData (Optional)
 Once you have the ResultSet or Connection objects,
you can obtain the Meta Data about the database
or the query
 This gives valuable information about the data that
you are retrieving or the database that you are
using
 ResultSetMetaData rsMeta = rs.getMetaData();
 DatabaseMetaData dbmetadata =
connection.getMetaData();
 There are approximately 150 methods in the
DatabaseMetaData class.
Create the metadata object
ADVANCE JAVA
Classified e-Material
ResultSetMetaData Example
ResultSetMetaData meta = rs.getMetaData();
//Return the column count
int iColumnCount = meta.getColumnCount();
for (int i =1 ; i <= iColumnCount ; i++){
System.out.println(“Column Name: " +
meta.getColumnName(i));
System.out.println(“Column Type" +
meta.getColumnType(i));
System.out.println("Display Size: " +
meta.getColumnDisplaySize(i) );
System.out.println("Precision: " +
meta.getPrecision(i));
}
No of Cols
Name of Col
Datatype of Col
Precision of Col
Col Display Size
ADVANCE JAVA
Classified e-Material
Summary
 Introduction to JDBC
 JDBC APIs
 JDBC Drivers
 Database URL
 7 Steps to use JDBC
 Load DB-specific JDBC driver
 Get a Connection object
 Get a Statement object
 Execute queries and/or updates
 Read results
 Read Meta-data (optional step)


Más contenido relacionado

La actualidad más candente

Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 

La actualidad más candente (20)

Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
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...
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Jdk,jre,jvm
Jdk,jre,jvmJdk,jre,jvm
Jdk,jre,jvm
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Php
PhpPhp
Php
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
JDBC
JDBCJDBC
JDBC
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 

Destacado

Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
myrajendra
 
Chapter 11.4
Chapter 11.4Chapter 11.4
Chapter 11.4
sotlsoc
 

Destacado (18)

Weather patterns
Weather patternsWeather patterns
Weather patterns
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
 
Swing
SwingSwing
Swing
 
Jtextarea
JtextareaJtextarea
Jtextarea
 
011 more swings_adv
011 more swings_adv011 more swings_adv
011 more swings_adv
 
Power editor basics
Power editor basicsPower editor basics
Power editor basics
 
Chapter 11.4
Chapter 11.4Chapter 11.4
Chapter 11.4
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
KMUTNB - Internet Programming 6/7
KMUTNB - Internet Programming 6/7KMUTNB - Internet Programming 6/7
KMUTNB - Internet Programming 6/7
 
Abzolute Logistic Solution
Abzolute Logistic SolutionAbzolute Logistic Solution
Abzolute Logistic Solution
 
java swing programming
java swing programming java swing programming
java swing programming
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
Java Swing
Java SwingJava Swing
Java Swing
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
java2 swing
java2 swingjava2 swing
java2 swing
 

Similar a JDBC

jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
web360
 

Similar a JDBC (20)

jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Data access
Data accessData access
Data access
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Lecture17
Lecture17Lecture17
Lecture17
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 

Más de Ankit Desai

Más de Ankit Desai (19)

java Jdbc
java Jdbc java Jdbc
java Jdbc
 
java code and document security
java code and document securityjava code and document security
java code and document security
 
Java Beans
Java BeansJava Beans
Java Beans
 
java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transfer
 
Java RMI
Java RMIJava RMI
Java RMI
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Presentation14 audio play
Presentation14 audio playPresentation14 audio play
Presentation14 audio play
 
Presentation15 parse xml
Presentation15 parse xmlPresentation15 parse xml
Presentation15 parse xml
 
Presentation11 sq lite
Presentation11 sq litePresentation11 sq lite
Presentation11 sq lite
 
Hadoop installation
Hadoop installationHadoop installation
Hadoop installation
 
Presentation10 view navigation
Presentation10 view navigationPresentation10 view navigation
Presentation10 view navigation
 
Presentation7 segment control
Presentation7 segment controlPresentation7 segment control
Presentation7 segment control
 
Presentation6 ui image_view
Presentation6 ui image_viewPresentation6 ui image_view
Presentation6 ui image_view
 
Presentation5 picker view
Presentation5 picker viewPresentation5 picker view
Presentation5 picker view
 
Presentation4 date picker
Presentation4 date pickerPresentation4 date picker
Presentation4 date picker
 
Presentation3 actionsheet alertview
Presentation3 actionsheet alertviewPresentation3 actionsheet alertview
Presentation3 actionsheet alertview
 
Presentation1 password
Presentation1 passwordPresentation1 password
Presentation1 password
 
Presentation2 gesture control
Presentation2 gesture controlPresentation2 gesture control
Presentation2 gesture control
 
Presentation8 silder switch_progress
Presentation8 silder switch_progressPresentation8 silder switch_progress
Presentation8 silder switch_progress
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

JDBC

  • 2. ADVANCE JAVA Author Profile  Ankit Desai  Ph.D. Scholar, IET, Ahmedabad University  Education: M. Tech. (C.E.), B. E. (I. T.)  Experience: 8 years (Academic and Research)  Research Interest: IoT, Big Data Analytics, Machine Learning, Data Mining, Algorithms. Classified e-Material 2
  • 3. ADVANCE JAVA Classified e-Material Java Database Connectivity JDBC Basics Application
  • 4. ADVANCE JAVA Classified e-Material Agenda  What is JDBC?  JDBC API  JDBC Driver  Database URL  Step By Step Usage of JDBC API  Load DB-specific JDBC driver  Get a Connection object  Get a Statement object  Execute queries and/or updates  Read results  Read Meta-data (optional step)  Close Statement and Connection objects
  • 5. ADVANCE JAVA What is JDBC?  Java Database Connectivity (JDBC) is a programming framework to get data from  databases  spreadsheets  flat files  Standard Java API for accessing relational database  Hides database specific details from application Classified e-Material DBMS Java Application JDBC Client Machine DBMS.propritary protocol Database Server
  • 6. ADVANCE JAVA Four types of JDBC Drivers Classified e-Material JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC ODBC Driver CLI (.lib) Middleware Server
  • 7. ADVANCE JAVA Classified e-Material JDBC API  Defines a set of Java Interfaces, which are implemented by vendor-specific JDBC Drivers  Applications use this set of Java interfaces for performing database operations JDBC API Layers Java Application JDBC API JDBC Manager JDBC Driver API JDBC NetDriver JDBC.ODBC Bridge ODBC Driver Driver 1 Driver 2
  • 8. ADVANCE JAVA Classified e-Material JDBC API  Majority of JDBC API is located in java.sql package  DriverManager, Connection, ResultSet, DatabaseMetaData, ResultSetMetaData, PreparedStatement, CallableStatement and Types  Other advanced functionality exists in the javax.sql package  DataSource
  • 9. ADVANCE JAVA JDBC Class Usage Classified e-Material DriverManager Driver Connection Statement ResultSet
  • 10. ADVANCE JAVA Classified e-Material JDBC Driver  Database specific implementation of JDBC interfaces  Every database server has corresponding JDBC driver(s)  You can see the list of available drivers from  http://industry.java.sun.com/products/jdbc/drivers
  • 11. ADVANCE JAVA Classified e-Material Database URL  Used to make a connection to the database  Can contain server, port, protocol etc…  jdbc:subprotocol_name:driver_dependant_databasename  Oracle thin driver  Jdbc:oracle:thin:@machinename:1521:dbname  Derby  jdbc:derby://localhost:1527/sample  Pointbase  jdbc:pointbase:server://localhost/sample
  • 12. ADVANCE JAVA Classified e-Material Agenda  What is JDBC?  Step By Step Usage of JDBC API
  • 13. ADVANCE JAVA Classified e-Material Steps of Using JDBC  1.Load DB-specific JDBC driver  2.Get a Connection object  3.Get a Statement object  4.Execute queries and/or updates  5.Read results  6.Read Meta-data (optional step)  7.Close Statement and Connection objects
  • 14. ADVANCE JAVA Classified e-Material 1. Load DB-Specific Database Driver  To manually load the database driver and register it with the DriverManager, load its class file  Class.forName(<database-driver>) try { // This loads an instance of the Pointbase DB Driver. // The driver has to be in the classpath. Class.forName("org.apache.derby.jdbc.ClientDriver") ; }catch (ClassNotFoundException cnfe){ System.out.println("" + cnfe); } Static Method of ClassClass Name Database Driver String
  • 15. ADVANCE JAVA Classified e-Material 2. Get a Connection Object  DriverManager class is responsible for selecting the database and and creating the database connection  Using DataSource is a prefered means of getting a conection object  Create the database connection as follows: try { Connection connection = DriverManager.getConnection("jdbc:derby://localhost :1527/sample", “app"," app "); } catch(SQLException sqle) { System.out.println("" + sqle); } Create the object of Connection Class
  • 16. ADVANCE JAVA Classified e-Material DriverManager & Connection  java.sql.DriverManager  getConnection(String url, String user, String password) throws SQLException  java.sql.Connection  Statement createStatement() throws SQLException  void close() throws SQLException  void setAutoCommit(boolean b) throws SQLException  void commit() throws SQLException  void rollback() throws SQLException
  • 17. ADVANCE JAVA Classified e-Material 3. Get a Statement Object  Create a Statement Object from Connection object  java.sql.Statement  ResultSet executeQuery(string sql)  int executeUpdate(String sql)  Example:  Statement statement = connection.createStatement();  The same Statement object can be used for many, unrelated queries Create Statement Object
  • 18. ADVANCE JAVA Classified e-Material 4. Executing Query or Update  From the Statement object, the 2 most used commands are  (a) QUERY (SELECT)  ResultSet rs = statement.executeQuery("select * from customer_tbl");  (b) ACTION COMMAND (UPDATE/DELETE)  int iReturnValue = statement.executeUpdate("update manufacture_tbl set name = ‘IBM' where mfr_num = 19985678"); Execute select query Execute update query
  • 19. ADVANCE JAVA Classified e-Material Steps of Using JDBC  1.Load DB-specific JDBC driver  2.Get a Connection object  3.Get a Statement object  4.Execute queries and/or updates  5.Read results  6.Read Meta-data (optional step)  7.Close Statement and Connection objects
  • 20. ADVANCE JAVA Classified e-Material 5. Reading Results  Loop through ResultSet retrieving information  java.sql.ResultSet  boolean next()  xxx getXxx(int columnNumber)  xxx getXxx(String columnName)  void close()  The iterator is initialized to a position before the first row  You must call next() once to move it to the first row
  • 21. ADVANCE JAVA Classified e-Material 5. Reading Results (Continued)  Once you have the ResultSet, you can easily retrieve the data by looping through it while (rs.next()){ // Wrong this will generate an error String value0 = rs.getString(0); // Correct! String value1 = rs.getString(1); int value2 = rs.getInt(2); int value3 = rs.getInt(“ADDR_LN1"); } Move to the next touple while end Index starts from 1
  • 22. ADVANCE JAVA Classified e-Material 5. Reading Results (Continued)  When retrieving data from the ResultSet, use the appropriate getXXX() method  getString()  getInt()  getDouble()  getObject()  There is an appropriate getXXX method of each java.sql.Types datatype
  • 23. ADVANCE JAVA Classified e-Material 6. Read ResultSet MetaData and DatabaseMetaData (Optional)  Once you have the ResultSet or Connection objects, you can obtain the Meta Data about the database or the query  This gives valuable information about the data that you are retrieving or the database that you are using  ResultSetMetaData rsMeta = rs.getMetaData();  DatabaseMetaData dbmetadata = connection.getMetaData();  There are approximately 150 methods in the DatabaseMetaData class. Create the metadata object
  • 24. ADVANCE JAVA Classified e-Material ResultSetMetaData Example ResultSetMetaData meta = rs.getMetaData(); //Return the column count int iColumnCount = meta.getColumnCount(); for (int i =1 ; i <= iColumnCount ; i++){ System.out.println(“Column Name: " + meta.getColumnName(i)); System.out.println(“Column Type" + meta.getColumnType(i)); System.out.println("Display Size: " + meta.getColumnDisplaySize(i) ); System.out.println("Precision: " + meta.getPrecision(i)); } No of Cols Name of Col Datatype of Col Precision of Col Col Display Size
  • 25. ADVANCE JAVA Classified e-Material Summary  Introduction to JDBC  JDBC APIs  JDBC Drivers  Database URL  7 Steps to use JDBC  Load DB-specific JDBC driver  Get a Connection object  Get a Statement object  Execute queries and/or updates  Read results  Read Meta-data (optional step) 