SlideShare uma empresa Scribd logo
1 de 17
JDBC
(Java Database Connectivity)
Overview (1/2)
 JDBC
 JDBC is a standard interface for connecting to relational databases
from Java
 The JDBC Classes and Interfaces are in the java.sql package
 JDBC is Java API for executing SQL statements

Provides a standard API for tool/database developers

Possible to write database applications using a pure Java API

Easy to send SQL statements to virtually any relational database
 What does JDBC do?
 Establish a connection with a database
 Send SQL statements
 Process the results
JDBC Driver
JAVA Applet/
Application Database
JDBC Call
Database
Command
 Reason for JDBC
 Database vendors (Microsoft Access, Oracle etc.) provide
proprietary (non standard) API for sending SQL to the server
and receiving results from it
 Languages such as C/C++ can make use of these proprietary
APIs directly

High performance

Can make use of non standard features of the database

All the database code needs to be rewritten if you change
database vendor or product
 JDBC is a vendor independent API for accessing relational
data from different database vendors in a consistent way
CCTM: Course material developed by James King (james.king@londonmet.ac.uk)
Overview (2/2)
History of JDBC (1/2)
 JDBC 1.0 released 9/1996.
 Contains basic functionality to connect to database, query database,
process results
 JDBC classes are part of java.sql package
 Comes with JDK 1.1
 JDBC 2.0 released 5/1998
 Comes with JDK 1.2
 javax.sql contains additional functionality
 Additional functionality:

Scroll in result set or move to specific row

Update database tables using Java methods instead of SQL
commands

Send multiple SQL statements to the database as a batch

Use of SQL3 datatypes as column values
History of JDBC (2/2)
 JDBC 3.0 released 2/2002
 Comes with Java 2, J2SE 1.4

Support for:

Connection pooling

Multiple result sets

Prepared statement pooling

Save points in transactions
JDBC Model
 JDBC consists of two parts:
 JDBC API, a purely Java-based API
 JDBC driver manager

Communicates with vendor-specific
drivers
 Connection con =
DriverManager.getConnection( "jd
bc:myDriver:myDatabase",
username, password);
JAVA Applet/
Application
JDBC API
Driver Manager
Driver API
Vendor Specific
JDBC Driver
JDBC-ODBC Bridge
Database
Vender Specific
ODBC Driver
Database
Java Application
Developer
JDBC Developer
Vender Specific
JDBC developer
JDBC Programming Steps
Connect
Query
Process Results
Close
1) Register the driver
2) Create a connection to the database
1) Create a statement
2) Query the database
1) Get a result set
2) Assign results to Java variables
1) Close the result set
2) Close the statement
3) Close the connection
Skeleton Code
Class.forName(DRIVERNAME);
Connection con = DriverManager.getConnection(
CONNECTIONURL, DBID, DBPASSWORD);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member);
While(rs.next())
{
Int x = rs.getInt(“a”);
String s = rs.getString(“b”);
Float f = rs.getFloat(“c”);
}
rs.close();
stmt.close();
con.close();
Loading a JDBC driver
Connecting to a database
Processing the result set
Closing the connections
Executing SQL
Step 1 : Loading a JDBC Driver
 A JDBC driver is needed to connect to a database
 Loading a driver requires the class name of the driver.
Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver
Oracle driver: oracle.jdbc.driver.OracleDriver
MySQL: com.mysql.jdbc.Driver
 Loaing the driver class
Class.forName("com.mysql.jdbc.Driver");
 It is possible to load several drivers.
 The class DriverManager manages the loaded driver(s)
Step 2 : Connecting to a Database (1/2)
 JDBC URL for a database
 Identifies the database to be connected
 Consists of three-part:
jdbc:<subprotocol>:<subname>
Protocol: JDBC is
the only protocol in
JDBC
Protocol: JDBC is
the only protocol in
JDBC
Subname: indicates the location and
name of the database to be
accessed. Syntax is driver specific
Subname: indicates the location and
name of the database to be
accessed. Syntax is driver specific
Sub-protocol:
identifies a
database
driver
Sub-protocol:
identifies a
database
driver
Ex) jdbc:mysql://oopsla.snu.ac.kr/mydb
The syntax for the name of the database is a little messy and is
unfortunately vendor specific
JDBC URL
Vendor of database, Location of
database server and name of
database
Username Password
Step 2 : Connecting to a Database (2/2)
 The DriverManager allows you to connect to a database using
the specified JDBC driver, database location, database name,
username and password.
 It returns a Connection object which can then be used to
communicate with the database.
Connection connection =
DriverManager.getConnection("jdbc:mysql://oopsla.snu.ac.kr/mydb",“useri
d",“password");
JDBC URL
Vendor of database, Location of
database server and name of
database
Username Password
Step 3 : Executing SQL (1/2)
 Statement object
 Can be obtained from a Connection object
 Sends SQL to the database to be executed
 Statement has three methods to execute a SQL statement:
 executeQuery() for QUERY statements

Returns a ResultSet which contains the query results
 executeUpdate() for INSERT, UPDATE, DELETE statements

Returns an integer, the number of affected rows from the SQL
 execute() for either type of statement
Statement statement = connection.createStatement();
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, STATUS from ACME_RENTALS");
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("delete from ACME_RENTAL_ITEMS
where rental_id = 1011");
Step 3 : Executing SQL (2/2)
 Execute a select statement
 Execute a delete statement
Step 4 : Processing the Results (1/2)
 JDBC returns the results of a query in a ResultSet object
 ResultSet object contains all of the rows which satisfied the conditions
in an SQL statement
 A ResultSet object maintains a cursor pointing to its current
row of data
 Use next() to step through the result set row by row

next() returns TRUE if there are still remaining records
 getString(), getInt(), and getXXX() assign each value to a Java
variable
Record 1 Record 2 Record 3 Record 4
ResultSetInternal Pointer
The internal pointer starts one before the first record
Step 4 : Processing the Results (2/2)
 Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”);
While (rs.next()){
int id = rs.getInt(“ID”);
String name = rs.getString(“name”);
float score = rs.getFloat(“score”);
System.out.println(“ID=” + id + “ ” + name + “ ” + score);}
NOTE
You must step the cursor to the first record before read the results
This code will not skip the first record
ID name score
1 James 90.5
2 Smith 45.7
3 Donald 80.2
Table1
Output
ID=1 James 90.5
ID=2 Smith 45.7
ID=3 Donald 80.2
Step 5 : Closing Database Connection
 It is a good idea to close the Statement and Connection objects
when you have finished with them
 Close the ResultSet object
rs.close();
 Close the Statement object
stmt.close();
 Close the connection
connection.close();
The PreparedStatement Object
 A PreparedStatement object holds precompiled SQL
statements
 Use this object for statements you want to execute more than
once
 A PreparedStatement can contain variables (?) that you supply
each time you execute the statement
// Create the prepared statement
PreparedStatement pstmt = con.prepareStatement(“
UPDATE table1 SET status = ? WHERE id =?”)
// Supply values for the variables
pstmt.setString (1, “out”);
pstmt.setInt(2, id);
// Execute the statement
pstmt.executeUpdate();

Mais conteúdo relacionado

Mais procurados (20)

Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Jdbc
JdbcJdbc
Jdbc
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
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
 
Distributed database
Distributed databaseDistributed database
Distributed database
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Jdbc
JdbcJdbc
Jdbc
 
Multi Tier Architecture
Multi Tier ArchitectureMulti Tier Architecture
Multi Tier Architecture
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 

Destaque

Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginersAmbarish Rai
 
Spring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou TvariSpring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou TvariRoman Pichlík
 
Java.sql package
Java.sql packageJava.sql package
Java.sql packagemyrajendra
 
KMUTNB - Internet Programming 6/7
KMUTNB - Internet Programming 6/7KMUTNB - Internet Programming 6/7
KMUTNB - Internet Programming 6/7phuphax
 
Abzolute Logistic Solution
Abzolute Logistic SolutionAbzolute Logistic Solution
Abzolute Logistic Solutionphuphax
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jspAnkit Minocha
 

Destaque (9)

Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Weather patterns
Weather patternsWeather patterns
Weather patterns
 
Spring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou TvariSpring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou Tvari
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
 
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
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 

Semelhante a Jdbc (database in java)

Semelhante a Jdbc (database in java) (20)

JDBC
JDBCJDBC
JDBC
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Lecture17
Lecture17Lecture17
Lecture17
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
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
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
JDBC
JDBCJDBC
JDBC
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
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
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc
JdbcJdbc
Jdbc
 

Último

BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfSuman Jyoti
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 

Último (20)

BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 

Jdbc (database in java)

  • 2. Overview (1/2)  JDBC  JDBC is a standard interface for connecting to relational databases from Java  The JDBC Classes and Interfaces are in the java.sql package  JDBC is Java API for executing SQL statements  Provides a standard API for tool/database developers  Possible to write database applications using a pure Java API  Easy to send SQL statements to virtually any relational database  What does JDBC do?  Establish a connection with a database  Send SQL statements  Process the results JDBC Driver JAVA Applet/ Application Database JDBC Call Database Command
  • 3.  Reason for JDBC  Database vendors (Microsoft Access, Oracle etc.) provide proprietary (non standard) API for sending SQL to the server and receiving results from it  Languages such as C/C++ can make use of these proprietary APIs directly  High performance  Can make use of non standard features of the database  All the database code needs to be rewritten if you change database vendor or product  JDBC is a vendor independent API for accessing relational data from different database vendors in a consistent way CCTM: Course material developed by James King (james.king@londonmet.ac.uk) Overview (2/2)
  • 4. History of JDBC (1/2)  JDBC 1.0 released 9/1996.  Contains basic functionality to connect to database, query database, process results  JDBC classes are part of java.sql package  Comes with JDK 1.1  JDBC 2.0 released 5/1998  Comes with JDK 1.2  javax.sql contains additional functionality  Additional functionality:  Scroll in result set or move to specific row  Update database tables using Java methods instead of SQL commands  Send multiple SQL statements to the database as a batch  Use of SQL3 datatypes as column values
  • 5. History of JDBC (2/2)  JDBC 3.0 released 2/2002  Comes with Java 2, J2SE 1.4  Support for:  Connection pooling  Multiple result sets  Prepared statement pooling  Save points in transactions
  • 6. JDBC Model  JDBC consists of two parts:  JDBC API, a purely Java-based API  JDBC driver manager  Communicates with vendor-specific drivers  Connection con = DriverManager.getConnection( "jd bc:myDriver:myDatabase", username, password); JAVA Applet/ Application JDBC API Driver Manager Driver API Vendor Specific JDBC Driver JDBC-ODBC Bridge Database Vender Specific ODBC Driver Database Java Application Developer JDBC Developer Vender Specific JDBC developer
  • 7. JDBC Programming Steps Connect Query Process Results Close 1) Register the driver 2) Create a connection to the database 1) Create a statement 2) Query the database 1) Get a result set 2) Assign results to Java variables 1) Close the result set 2) Close the statement 3) Close the connection
  • 8. Skeleton Code Class.forName(DRIVERNAME); Connection con = DriverManager.getConnection( CONNECTIONURL, DBID, DBPASSWORD); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member); While(rs.next()) { Int x = rs.getInt(“a”); String s = rs.getString(“b”); Float f = rs.getFloat(“c”); } rs.close(); stmt.close(); con.close(); Loading a JDBC driver Connecting to a database Processing the result set Closing the connections Executing SQL
  • 9. Step 1 : Loading a JDBC Driver  A JDBC driver is needed to connect to a database  Loading a driver requires the class name of the driver. Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver Oracle driver: oracle.jdbc.driver.OracleDriver MySQL: com.mysql.jdbc.Driver  Loaing the driver class Class.forName("com.mysql.jdbc.Driver");  It is possible to load several drivers.  The class DriverManager manages the loaded driver(s)
  • 10. Step 2 : Connecting to a Database (1/2)  JDBC URL for a database  Identifies the database to be connected  Consists of three-part: jdbc:<subprotocol>:<subname> Protocol: JDBC is the only protocol in JDBC Protocol: JDBC is the only protocol in JDBC Subname: indicates the location and name of the database to be accessed. Syntax is driver specific Subname: indicates the location and name of the database to be accessed. Syntax is driver specific Sub-protocol: identifies a database driver Sub-protocol: identifies a database driver Ex) jdbc:mysql://oopsla.snu.ac.kr/mydb The syntax for the name of the database is a little messy and is unfortunately vendor specific
  • 11. JDBC URL Vendor of database, Location of database server and name of database Username Password Step 2 : Connecting to a Database (2/2)  The DriverManager allows you to connect to a database using the specified JDBC driver, database location, database name, username and password.  It returns a Connection object which can then be used to communicate with the database. Connection connection = DriverManager.getConnection("jdbc:mysql://oopsla.snu.ac.kr/mydb",“useri d",“password"); JDBC URL Vendor of database, Location of database server and name of database Username Password
  • 12. Step 3 : Executing SQL (1/2)  Statement object  Can be obtained from a Connection object  Sends SQL to the database to be executed  Statement has three methods to execute a SQL statement:  executeQuery() for QUERY statements  Returns a ResultSet which contains the query results  executeUpdate() for INSERT, UPDATE, DELETE statements  Returns an integer, the number of affected rows from the SQL  execute() for either type of statement Statement statement = connection.createStatement();
  • 13. Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery ("select RENTAL_ID, STATUS from ACME_RENTALS"); Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("delete from ACME_RENTAL_ITEMS where rental_id = 1011"); Step 3 : Executing SQL (2/2)  Execute a select statement  Execute a delete statement
  • 14. Step 4 : Processing the Results (1/2)  JDBC returns the results of a query in a ResultSet object  ResultSet object contains all of the rows which satisfied the conditions in an SQL statement  A ResultSet object maintains a cursor pointing to its current row of data  Use next() to step through the result set row by row  next() returns TRUE if there are still remaining records  getString(), getInt(), and getXXX() assign each value to a Java variable Record 1 Record 2 Record 3 Record 4 ResultSetInternal Pointer The internal pointer starts one before the first record
  • 15. Step 4 : Processing the Results (2/2)  Example Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”); While (rs.next()){ int id = rs.getInt(“ID”); String name = rs.getString(“name”); float score = rs.getFloat(“score”); System.out.println(“ID=” + id + “ ” + name + “ ” + score);} NOTE You must step the cursor to the first record before read the results This code will not skip the first record ID name score 1 James 90.5 2 Smith 45.7 3 Donald 80.2 Table1 Output ID=1 James 90.5 ID=2 Smith 45.7 ID=3 Donald 80.2
  • 16. Step 5 : Closing Database Connection  It is a good idea to close the Statement and Connection objects when you have finished with them  Close the ResultSet object rs.close();  Close the Statement object stmt.close();  Close the connection connection.close();
  • 17. The PreparedStatement Object  A PreparedStatement object holds precompiled SQL statements  Use this object for statements you want to execute more than once  A PreparedStatement can contain variables (?) that you supply each time you execute the statement // Create the prepared statement PreparedStatement pstmt = con.prepareStatement(“ UPDATE table1 SET status = ? WHERE id =?”) // Supply values for the variables pstmt.setString (1, “out”); pstmt.setInt(2, id); // Execute the statement pstmt.executeUpdate();

Notas do Editor

  1. Dynamically Executing an Unknown SQL Statement The following example uses execute() to dynamically execute an unknown statement: public void executeStmt (String statement) throws SQLException { Statement stmt = conn.createStatement(); // Execute the statement boolean result = stmt.execute(statement); if (result) {// statement was a query ResultSet rset = stmt.getResultSet(); // Process the results ... } else {// statement was an update or DDL int updateCount = stmt.getUpdateCount(); // Process the results ... }}