SlideShare a Scribd company logo
1 of 29
Basics of JDBC
Overview
• What is JDBC?
• Why need an application other than DBMS?
• How JDBC can help?
• JDBC Steps
• Transactions in JDBC
• JDBC Drivers
• Summary
What is JDBC?
• JDBC is: a Sun trademark
– is often taken to stand for Java Database Connectivity.
– is a Java API for connecting programs written in Java to the data
in relational databases.
– consists of a set of classes and interfaces written in the Java
programming language.
– provides a standard API for tool/database developers and makes it
possible to write database applications using a pure Java API.
– The standard defined by Sun Microsystems, allowing individual
providers to implement and extend the standard with their own
JDBC drivers.
JDBC
• Java is very standardized, but there are many versions of SQL
• JDBC is a means of accessing SQL databases from Java
– JDBC is a standardized API for use by Java programs
– JDBC is also a specification for how third-party vendors should write database
drivers to access specific SQL versions
• JDBC:
– establishes a connection with a database
– sends SQL statements
– processes the results.
The need of an application
• Databases offer structured storing, easy retrieval and
processing of data
• The maintenance, however, can be tedious
Suppose you manage a database store on an SQL server. Then you need to
have a knowledge on SQL in order to retrieve or update data. This will not be
that pleasant for you. Will it?
• An application in between can do the job for you
The application will deal with the database while you interact with the user-
friendly GUI
JDBC
• Java Database Connectivity
• Provides a Java API to access SQL databases
The JDBC API
• The JDBC API contains methods to communicate with DBMS or
RDBMS
• The JDBC API uses the JDBC driver to carry out it tasks
• The JDBC API & Driver enables a Java application to:
1. Establish a connection with a data source
2. Send queries and update statements to the data source
3. Process the results
Java Program JDBC API JDBC Driver Database
The process of accessing the database
JDBC API
• The JDBC API supports both two-tier and three-tier models for
database access.
• Two-tier model -- a Java applet or application interacts directly
with the database.
• Three-tier model -- introduces a middle-level server for
execution of business logic:
– the middle tier to maintain control over data access.
– the user can employ an easy-to-use higher-level API which is translated by the
middle tier into the appropriate low-level calls.
The JDBC API
• The JDBC API supports both two-tier and three-tier models
Java Application
DBMS
JDBC
Client machine
DBMS – proprietary protocol
Database server
Two-tier model
Java applet or
HTML browser
DBMS
Application
server (Java)
JDBC
Client machine (GUI)
HTTP, RMI, CORBA or other calls
Server machine
(business logic)
DBMS – proprietary protocol
Database server
Three-tier model
JDBC Classes
• java.sql.
– DriverManager
• getConnection
– Connection
• createStatement
– Statement
• execute, executeQuery, executeBatch, executeUpdate
– ResultSet
• next, getString, getInt, getDate, getMetaData
– ResultSetMetadata
• getColumnCount, getColumnName, getColumnType
JDBC Steps
1. Instantiate proper driver
2. Open connection to database
3. Connect to database
4. Query database (or insert/update/delete)
5. Process the result
6. Close connection to database
1. Instantiate Driver
• Class.forName(“driver class”)
• Driver class is vendor dependent, e.g.,
– sun.jdbc.odbc.JdbcOdbcDriver
• JDBC-ODBC bridge used to access ODBC Sources
– com.mysql.jdbc.Driver
• driver to access MySQL database
– com.sybase.jdbc2.jdbc.SybDriver
• driver to access Sybase database
2. Open Connection
• DriverManager.getConnection(url)
or
• DriverManager.getConnection(url, user, pwd) return Connection
• URL is jdbc:<subprotocol>:<subname>
– e.g., jdbc:odbc:someDB
• jdbc:<subprotocol>://<host>:<port>/<db>
– jdbc:mysql://localhost:3306/testDB
3. Connect to database
• Load JDBC driver
– Class.forName("com.mysql.jdbc.Driver").newInstance();
• Make connection
– Connection conn = DriverManager.getConnection(url);
• URL
– Format: jdbc:<subprotocol>://<host>:<port>/<db>
– jdbc:mysql://localhost:3306/testDB
4. Query database
a. Create statement
– Statement stmt = conn.createStatement();
– stmt object sends SQL commands to database
– Methods
• executeQuery() for SELECT statements
• executeUpdate() for INSERT, UPDATE, DELETE, statements
b. Send SQL statements
– stmt.executeQuery(“SELECT …”);
– stmt.executeUpdate(“INSERT …”);
5. Process results
• Result of a SELECT statement (rows/columns) returned as a ResultSet object
– ResultSet rs = stmt.executeQuery("SELECT * FROM users");
• Step through each row in the result
– rs.next()
• Get column values in a row
– String userid = rs.getString(“userid”);
– int type = rs.getInt(“type”);
users table
userid firstname lastname password type
Bob Bob King cat 0
John John Smith pass 1
Print the users table
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
String userid = rs.getString(1);
String firstname = rs.getString(“firstname”);
String lastname = rs.getString(“lastname”);
String password = rs.getString(4);
int type = rs.getInt(“type”);
System.out.println(userid + ” ” + firstname + ” ” +
lastname + ” ” + password + ” ” + type);
}
users table
userid firstname lastname password type
Bob Bob King cat 0
John John Smith pass 1
Add a row to the users table
String str = "INSERT INTO users VALUES('Bob', 'Bob', 'King',
'cat', 0)”;
//Returns number of rows in table
int rows = stmt.executeUpdate(str);
users table
userid firstname lastname password type
Bob Bob King cat 0
6. Closing connections
• Close the ResultSet object
– rs.close();
• Close the Statement object
– stmt.close();
• Close the connection
– conn.close();
import java.sql.*;
public class Tester {
public static void main(String[] args) {
try {
// Load JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Make connection
String url = “jdbc:mysql://localhost:3306/testDB”;
Connection conn = DriverManager.getConnection(url, ”root”, ”rev”);
// Create statement
Statement stmt = conn.createStatement();
// Print the users table
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
...
}
// Cleanup
rs.close(); stmt.close(); conn.close();
}
catch (Exception e) {
System.out.println("exception " + e);
}
}
Transactions
• Currently every executeUpdate() is “finalized”
right away
• Sometimes want to a set of updates to all fail or
all succeed
– E.g. add to Appointments and Bookings tables
– Treat both inserts as one transaction
• Transaction
– Used to group several SQL statements together
– Either all succeed or all fail
Transactions
• Commit
– Execute all statements as one unit
– “Finalize” updates
• Rollback
– Abort transaction
– All uncommited statements are discarded
– Revert database to original state
Transactions in JDBC
• Disable auto-commit for the connection
– conn.setAutoCommit(false);
• Call necessary executeUpdate() statements
• Commit or rollback
– conn.commit();
– conn.rollback();
JDBC Driver
• There are four flavors of JDBC
JDBC-ODBC Bridge (Type 1 driver)
Native-API/partly-Java driver (Type 2 driver)
Net-protocol/all-Java driver (Type 3 driver)
Native-protocol/all-Java driver (Type 4 driver)
JDBC Driver
• We will use the,
Native-protocol/all-Java driver
Java
Application
Native-protocol/all-Java
driver
Database
server
Functionality of Type 4 driver
On The Job
• Required software
Java-2 JVM s including JDK – 1.4x or newer to compile
MySQL server version 4.1 or newer
MySQL Connector/J
Note: We have used MySQL as the database server and
MySQL Connector/J as the database specific JDBC
driver
Example
import java.sql.*;
import java.io.*;
class JDBC
{
public static void main(String[] args)
{
try
{
Connection conn;
Statement stmt;
String Query;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost/game","root","passwo
rd");
stmt=conn.createStatement();
Query="select * from table1";
rs=stmt.executeQuery(Query);
while(rs.next())
{ String s = rs.getString(1);
System.out.println(s);
}
rs.close();
conn.close();
}
catch(SQLException sqle)
{
System.out.println(sqle);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Loading the Driver
a) Import statements
import java.sql.*;
b) Loading the database driver
Class.forName("com.mysql.jdbc.Driver");
- We load the driver class by calling Class.forName() with
the Driver
class name as an argument
- If the class name is jdbc.DriverXYZ , you would load the
driver with the
following line of code: Class.forName("jdbc.DriverXYZ");
- Once loaded, the Driver class creates an instance of itself.

More Related Content

Similar to JDBC Basics (20)

Prashanthi
PrashanthiPrashanthi
Prashanthi
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Jdbc
JdbcJdbc
Jdbc
 
java.pptx
java.pptxjava.pptx
java.pptx
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
jdbc_unit2.ppt
jdbc_unit2.pptjdbc_unit2.ppt
jdbc_unit2.ppt
 
PROGRAMMING IN JAVA- unit 5-part II
PROGRAMMING IN JAVA- unit 5-part IIPROGRAMMING IN JAVA- unit 5-part II
PROGRAMMING IN JAVA- unit 5-part II
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
 
jdbc.ppt
jdbc.pptjdbc.ppt
jdbc.ppt
 

More from Jayaprasanna4

Human computer Interaction ch1-the human.pdf
Human computer Interaction ch1-the human.pdfHuman computer Interaction ch1-the human.pdf
Human computer Interaction ch1-the human.pdfJayaprasanna4
 
computer Networks Error Detection and Correction.ppt
computer Networks Error Detection and Correction.pptcomputer Networks Error Detection and Correction.ppt
computer Networks Error Detection and Correction.pptJayaprasanna4
 
HUman computer Interaction Socio-organizational Issues.ppt
HUman computer Interaction Socio-organizational Issues.pptHUman computer Interaction Socio-organizational Issues.ppt
HUman computer Interaction Socio-organizational Issues.pptJayaprasanna4
 
human computer Interaction cognitive models.ppt
human computer Interaction cognitive models.ppthuman computer Interaction cognitive models.ppt
human computer Interaction cognitive models.pptJayaprasanna4
 
World wide web and Hyper Text Markup Language
World wide web and Hyper Text Markup LanguageWorld wide web and Hyper Text Markup Language
World wide web and Hyper Text Markup LanguageJayaprasanna4
 
Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.pptJayaprasanna4
 
Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.pptJayaprasanna4
 
Lecture 19- Multicasting.ppt
Lecture 19- Multicasting.pptLecture 19- Multicasting.ppt
Lecture 19- Multicasting.pptJayaprasanna4
 
connecting LANs.pptx
connecting LANs.pptxconnecting LANs.pptx
connecting LANs.pptxJayaprasanna4
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.pptJayaprasanna4
 
connecting devices.ppt
connecting devices.pptconnecting devices.ppt
connecting devices.pptJayaprasanna4
 

More from Jayaprasanna4 (20)

Human computer Interaction ch1-the human.pdf
Human computer Interaction ch1-the human.pdfHuman computer Interaction ch1-the human.pdf
Human computer Interaction ch1-the human.pdf
 
computer Networks Error Detection and Correction.ppt
computer Networks Error Detection and Correction.pptcomputer Networks Error Detection and Correction.ppt
computer Networks Error Detection and Correction.ppt
 
HUman computer Interaction Socio-organizational Issues.ppt
HUman computer Interaction Socio-organizational Issues.pptHUman computer Interaction Socio-organizational Issues.ppt
HUman computer Interaction Socio-organizational Issues.ppt
 
human computer Interaction cognitive models.ppt
human computer Interaction cognitive models.ppthuman computer Interaction cognitive models.ppt
human computer Interaction cognitive models.ppt
 
World wide web and Hyper Text Markup Language
World wide web and Hyper Text Markup LanguageWorld wide web and Hyper Text Markup Language
World wide web and Hyper Text Markup Language
 
CI-Monte-Carlo.ppt
CI-Monte-Carlo.pptCI-Monte-Carlo.ppt
CI-Monte-Carlo.ppt
 
Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.ppt
 
Cost effort.ppt
Cost effort.pptCost effort.ppt
Cost effort.ppt
 
Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.ppt
 
unit-1.ppt
unit-1.pptunit-1.ppt
unit-1.ppt
 
BGP.ppt
BGP.pptBGP.ppt
BGP.ppt
 
Lecture 19- Multicasting.ppt
Lecture 19- Multicasting.pptLecture 19- Multicasting.ppt
Lecture 19- Multicasting.ppt
 
line coding.ppt
line coding.pptline coding.ppt
line coding.ppt
 
error detection.ppt
error detection.ppterror detection.ppt
error detection.ppt
 
connecting LANs.pptx
connecting LANs.pptxconnecting LANs.pptx
connecting LANs.pptx
 
CS1302 06NOV.pdf
CS1302 06NOV.pdfCS1302 06NOV.pdf
CS1302 06NOV.pdf
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 
connecting devices.ppt
connecting devices.pptconnecting devices.ppt
connecting devices.ppt
 
ARP.ppt
ARP.pptARP.ppt
ARP.ppt
 
Transport_layer.ppt
Transport_layer.pptTransport_layer.ppt
Transport_layer.ppt
 

Recently uploaded

ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 

Recently uploaded (20)

ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 

JDBC Basics

  • 2. Overview • What is JDBC? • Why need an application other than DBMS? • How JDBC can help? • JDBC Steps • Transactions in JDBC • JDBC Drivers • Summary
  • 3. What is JDBC? • JDBC is: a Sun trademark – is often taken to stand for Java Database Connectivity. – is a Java API for connecting programs written in Java to the data in relational databases. – consists of a set of classes and interfaces written in the Java programming language. – provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API. – The standard defined by Sun Microsystems, allowing individual providers to implement and extend the standard with their own JDBC drivers.
  • 4. JDBC • Java is very standardized, but there are many versions of SQL • JDBC is a means of accessing SQL databases from Java – JDBC is a standardized API for use by Java programs – JDBC is also a specification for how third-party vendors should write database drivers to access specific SQL versions • JDBC: – establishes a connection with a database – sends SQL statements – processes the results.
  • 5. The need of an application • Databases offer structured storing, easy retrieval and processing of data • The maintenance, however, can be tedious Suppose you manage a database store on an SQL server. Then you need to have a knowledge on SQL in order to retrieve or update data. This will not be that pleasant for you. Will it? • An application in between can do the job for you The application will deal with the database while you interact with the user- friendly GUI
  • 6. JDBC • Java Database Connectivity • Provides a Java API to access SQL databases
  • 7. The JDBC API • The JDBC API contains methods to communicate with DBMS or RDBMS • The JDBC API uses the JDBC driver to carry out it tasks • The JDBC API & Driver enables a Java application to: 1. Establish a connection with a data source 2. Send queries and update statements to the data source 3. Process the results Java Program JDBC API JDBC Driver Database The process of accessing the database
  • 8. JDBC API • The JDBC API supports both two-tier and three-tier models for database access. • Two-tier model -- a Java applet or application interacts directly with the database. • Three-tier model -- introduces a middle-level server for execution of business logic: – the middle tier to maintain control over data access. – the user can employ an easy-to-use higher-level API which is translated by the middle tier into the appropriate low-level calls.
  • 9. The JDBC API • The JDBC API supports both two-tier and three-tier models Java Application DBMS JDBC Client machine DBMS – proprietary protocol Database server Two-tier model Java applet or HTML browser DBMS Application server (Java) JDBC Client machine (GUI) HTTP, RMI, CORBA or other calls Server machine (business logic) DBMS – proprietary protocol Database server Three-tier model
  • 10. JDBC Classes • java.sql. – DriverManager • getConnection – Connection • createStatement – Statement • execute, executeQuery, executeBatch, executeUpdate – ResultSet • next, getString, getInt, getDate, getMetaData – ResultSetMetadata • getColumnCount, getColumnName, getColumnType
  • 11. JDBC Steps 1. Instantiate proper driver 2. Open connection to database 3. Connect to database 4. Query database (or insert/update/delete) 5. Process the result 6. Close connection to database
  • 12. 1. Instantiate Driver • Class.forName(“driver class”) • Driver class is vendor dependent, e.g., – sun.jdbc.odbc.JdbcOdbcDriver • JDBC-ODBC bridge used to access ODBC Sources – com.mysql.jdbc.Driver • driver to access MySQL database – com.sybase.jdbc2.jdbc.SybDriver • driver to access Sybase database
  • 13. 2. Open Connection • DriverManager.getConnection(url) or • DriverManager.getConnection(url, user, pwd) return Connection • URL is jdbc:<subprotocol>:<subname> – e.g., jdbc:odbc:someDB • jdbc:<subprotocol>://<host>:<port>/<db> – jdbc:mysql://localhost:3306/testDB
  • 14. 3. Connect to database • Load JDBC driver – Class.forName("com.mysql.jdbc.Driver").newInstance(); • Make connection – Connection conn = DriverManager.getConnection(url); • URL – Format: jdbc:<subprotocol>://<host>:<port>/<db> – jdbc:mysql://localhost:3306/testDB
  • 15. 4. Query database a. Create statement – Statement stmt = conn.createStatement(); – stmt object sends SQL commands to database – Methods • executeQuery() for SELECT statements • executeUpdate() for INSERT, UPDATE, DELETE, statements b. Send SQL statements – stmt.executeQuery(“SELECT …”); – stmt.executeUpdate(“INSERT …”);
  • 16. 5. Process results • Result of a SELECT statement (rows/columns) returned as a ResultSet object – ResultSet rs = stmt.executeQuery("SELECT * FROM users"); • Step through each row in the result – rs.next() • Get column values in a row – String userid = rs.getString(“userid”); – int type = rs.getInt(“type”); users table userid firstname lastname password type Bob Bob King cat 0 John John Smith pass 1
  • 17. Print the users table ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { String userid = rs.getString(1); String firstname = rs.getString(“firstname”); String lastname = rs.getString(“lastname”); String password = rs.getString(4); int type = rs.getInt(“type”); System.out.println(userid + ” ” + firstname + ” ” + lastname + ” ” + password + ” ” + type); } users table userid firstname lastname password type Bob Bob King cat 0 John John Smith pass 1
  • 18. Add a row to the users table String str = "INSERT INTO users VALUES('Bob', 'Bob', 'King', 'cat', 0)”; //Returns number of rows in table int rows = stmt.executeUpdate(str); users table userid firstname lastname password type Bob Bob King cat 0
  • 19. 6. Closing connections • Close the ResultSet object – rs.close(); • Close the Statement object – stmt.close(); • Close the connection – conn.close();
  • 20. import java.sql.*; public class Tester { public static void main(String[] args) { try { // Load JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Make connection String url = “jdbc:mysql://localhost:3306/testDB”; Connection conn = DriverManager.getConnection(url, ”root”, ”rev”); // Create statement Statement stmt = conn.createStatement(); // Print the users table ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { ... } // Cleanup rs.close(); stmt.close(); conn.close(); } catch (Exception e) { System.out.println("exception " + e); } }
  • 21. Transactions • Currently every executeUpdate() is “finalized” right away • Sometimes want to a set of updates to all fail or all succeed – E.g. add to Appointments and Bookings tables – Treat both inserts as one transaction • Transaction – Used to group several SQL statements together – Either all succeed or all fail
  • 22. Transactions • Commit – Execute all statements as one unit – “Finalize” updates • Rollback – Abort transaction – All uncommited statements are discarded – Revert database to original state
  • 23. Transactions in JDBC • Disable auto-commit for the connection – conn.setAutoCommit(false); • Call necessary executeUpdate() statements • Commit or rollback – conn.commit(); – conn.rollback();
  • 24. JDBC Driver • There are four flavors of JDBC JDBC-ODBC Bridge (Type 1 driver) Native-API/partly-Java driver (Type 2 driver) Net-protocol/all-Java driver (Type 3 driver) Native-protocol/all-Java driver (Type 4 driver)
  • 25. JDBC Driver • We will use the, Native-protocol/all-Java driver Java Application Native-protocol/all-Java driver Database server Functionality of Type 4 driver
  • 26. On The Job • Required software Java-2 JVM s including JDK – 1.4x or newer to compile MySQL server version 4.1 or newer MySQL Connector/J Note: We have used MySQL as the database server and MySQL Connector/J as the database specific JDBC driver
  • 27. Example import java.sql.*; import java.io.*; class JDBC { public static void main(String[] args) { try { Connection conn; Statement stmt; String Query; ResultSet rs; Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost/game","root","passwo rd"); stmt=conn.createStatement();
  • 28. Query="select * from table1"; rs=stmt.executeQuery(Query); while(rs.next()) { String s = rs.getString(1); System.out.println(s); } rs.close(); conn.close(); } catch(SQLException sqle) { System.out.println(sqle); } catch(Exception e) { System.out.println(e); } } }
  • 29. Loading the Driver a) Import statements import java.sql.*; b) Loading the database driver Class.forName("com.mysql.jdbc.Driver"); - We load the driver class by calling Class.forName() with the Driver class name as an argument - If the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: Class.forName("jdbc.DriverXYZ"); - Once loaded, the Driver class creates an instance of itself.