SlideShare ist ein Scribd-Unternehmen logo
1 von 30
June 21, 2017 www.snipe.co.in 1
Prepared :Snipe Team
June 21, 2017 2
Java Database Connection
(JDBC)
June 21, 2017 3
JDBC
• JDBC is an API for the Java programming language that
defines how a client may access a database. It provides
methods for querying and updating data in a database.
• JDBC
- is the Java object version of Microsoft ODBC.
- defines Java class wrappers for SQL database access.
- can access almost any database service.
- JDBC drivers are available from almost any Java vendor.
- java.sql.* package is now part of the Java core.
- compliance means the drivers support SQL92.
- must implement the java.sql.* classes.
- must be thread safe.
• JDBC Naming Convention.
"jdbc:oracle:thin:@oracle-prod:1521:OPROD“ , "scott", "tiger”
The first string is the URL for the database including the
protocol (jdbc), the vendor (oracle), the driver (thin), the
server (oracle-prod), the port number (1521), and a
server instance (OPROD).
Second is the Username.
Third is the Password.
• JDBC Classes
– JDBC Core Interfaces
– Java Language extensions
– Java Utility Extensions
– SQL Metadata Interfaces.
June 21, 2017 4
JDBC
• JDBC is a Java-based data access technology (Java
Standard Edition platform) from Oracle Corporation.
• Sun Microsystems released JDBC as part of JDK 1.1 on
February 19, 1997.[1] It has since formed part of the
Java Standard Edition.
• The JDBC classes are contained in the Java
package java.sql and javax.sql.
• Starting with version 3.1, JDBC has been developed under
the Java Community Process. JSR 54 specifies JDBC 3.0
(included in J2SE 1.4), JSR 114 specifies the JDBC Rowset
additions, and JSR 221 is the specification of JDBC 4.0
(included in Java SE 6).[2]
• The latest version, JDBC 4.1, is specified by a maintenance
release of JSR 221[3] and is included in Java SE 7.[4]
June 21, 2017 5
JDBC History
• JDBC 2.0
– Support for data types, such as objects, arrays, and large objects
(LOBs). This is handled through the standard java.sql package.
– Support for standard features, such as result set enhancements and
update batching. This is handled through standard objects, such
as Connection,ResultSet, and PreparedStatement, under JDK 1.2.x
and later.
– Support for extended features, such as features of the JDBC 2.0
optional package, also known as the standard extension application
programming interface (API), including data sources, connection
pooling, and distributed transactions
June 21, 2017 6
JDBC Example
• JDBC 2.0
– Transaction Savepoints
– Retrieval of Auto-Generated Keys
– JDBC 3.0 LOB Interface Methods
– Result Set Holdability
• JDBC 4.0
– Wrapper Pattern Support
– Enhanced Exception Hierarchy and SQLException
– The RowId Data Type
– LOB Creation
– National Language Character Set Support
• JDBC 4.1
– The ability to use a try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement
– RowSet 1.1: The introduction of the RowSetFactory interface and the
RowSetProvider class, which enable you to create all types of row sets
supported by your JDBC driver.
June 21, 2017 7
JDBC Example
• Classes
– locate DBMS drivers - DriverManagerClass
• locates the driver for DB you specify
– establish connections
• commit, rollback and the DB isolation level
– submit SQL statements
• 2 extensions
– Prepared statement - precompile and execute
– Callable statement - stored procedures
– process result set
• manipulate the cursor and get back results
June 21, 2017 8
JDBC Core
June 21, 2017 9
JDBC Drivers
- JDBC drivers implement the defined interfaces in the JDBC
API for interacting with your database server
- Using JDBC drivers enable you to open database
Connections and to interact with it by sending SQL or database
commands then receiving results with Java
June 21, 2017 10
Type 1 JDBC Drivers
• Type 1 : This driver converts JDBC calls to ODBC calls
through JDBC-ODBC Bridge driver which in turn converts to
database calls. Client requires ODBC libraries.
• a JDBC bridge is used to access ODBC drivers installed on
each client machine. Using ODBC requires configuring on
your system a Data Source Name (DSN) that represents the
target database.
June 21, 2017 11
Type 2 JDBC Drivers
• Type 2 : This driver converts JDBC calls to database
specific native calls. Client requires database specific
libraries.
• In a Type 2 driver, JDBC API calls are converted into native
C/C++ API calls which are unique to the database. These
drivers typically provided by the database vendors and used
in the same manner as the JDBC-ODBC Bridge, the vendor-
specific driver must be installed on each client machine
• E.g:- Oracle call Interface(OCI)
June 21, 2017 12
Type 3 JDBC Drivers
• Type 3 : This driver passes calls to proxy server through
network protocol which in turn converts to database calls and
passes through database specific protocol. Client doesn't
require any driver.
• In a Type 3 driver, a three-tier approach is used to accessing
databases. The JDBC clients use standard network sockets to
communicate with an middleware application server.
June 21, 2017 13
Type 4 JDBC Drivers
• Type 4 This driver directly calls database. Client doesn't
require any driver.
• In a Type 4 driver, a pure Java-based driver that
communicates directly with vendor's database through socket
connection. This is the highest performance driver available
for the database and is usually provided by the vendor itself.
June 21, 2017 14
Benchmarking JDBC Drivers
• Type 4 - Accessing one type of database, such as Oracle,
Sybase, or MySQL.
• Type 3 - Accessing Multiple types of database at the same
time
• Type 2 - In case 3 or 4 not available on your machine
• Type 1 - Drivers are not considered for deployment, only for
development and testing
• Import the JDBC Package
• Set useful static class variables for driver, DBMS URI,
credentials, etc.
• Register appropriate driver with the DriverManager class
• Set connection Properties (typically credentials)
• Invoke the Connection
• Create SQL statement in a String
• Invoke Statement on connection
• Execute SQL statement via appropriate method on
Statement object.
Continued…
June 21, 2017 15
Typical Steps
• execute(...), executeQuery(...) for SELECT to receive
ResultSet/s.
• executeUpdate(...) for INS/DEL/UPD or DDLs, receive
integer value indicating row count .
• automatic commit, unless disabled, in which case an explicit
COMMIT must be executed to save changes to database.
• Check for Exceptions.
• Process ResultSet
• Close ResultSet and Statement
• Unless multiple transactions, then redefine and reuse
• Cycle for further operations
• Close Connection
June 21, 2017 16
Typical Steps
• oracle.jdbc.driver (classes to support database access and
updates in Oracle type formats)
• Load the Oracle JDBC driver
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
or
Class.forName ("oracle.jdbc.driver.OracleDriver");
• Connect to the database
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@learning", “root", “pwd");
June 21, 2017 17
Registering & Connecting:The DriverManager Class
• Code for creating a connection using JDBC with Oracle
try
{ // register the driver to connect to oracle
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
// db_con is a connection object that lets us connect to the
// database with specified URL/userid/password
Connection db_con = DriverManager.getConnection
("jdbc:oracle:thin:@llama.its.monash.edu.au:1521:CSE
5200A", "studentid", "password");
System.out.println("Connection Success");
} catch(SQLException f ){
// gives error if the above did not succeed.
System.out.println("Connection Failed. SQL Exception");
• }
June 21, 2017 18
Sample Code
• Code to retrieve data from the Database using the previously
created JDBC Connection object.
try
{ // statement object stmt created to execute queries using
//db_con
Statement stmt = db_con.createStatement();
// resultset is an object that holds the result of the query
ResultSet rset = stmt.executeQuery ("SELECT * FROM
authors");
// looping through the resultset object till end
while (rset.next()){
// getString gets the string data in col 1 of result
// and we would have rset.getInt(2) if col 2 was an integer
System.out.println (rset.getString(1));
}June 21, 2017 19
Sample Code
} catch(SQLException f) {
// error handling for above
System.out.println("Cannot retrieve data SQL Exception
occured");
}
June 21, 2017 20
Sample Code
• Connection Interface
– Session between application and database
– Specified by location (URI) and credentials
• Commit/Rollback
– conn.commit();
– conn.rollback();
• Set Autocommit off
– after connect but before any statement
• conn.setAutoCommit (false);
June 21, 2017 21
Transactions:The Connection Interface
• Statement stmt = conn.createStatement ();
• stmt.execute (“select empno from emp”);
– no parameters
• PreparedStatement pmst = conn.prepareStatement
(“insert into emp (EMPNO, EMPNAME) values (?, ?)”);
- setting and getting parameters in next slides.
• pstmt.execute();
• selectText = "SELECT firstname,lastname FROM
addresses";
Continued…
June 21, 2017 22
Creating a Statement Object:Connection Interface
• Statement selectStmt = dbConnection.createStatement();
• ResultSet result = selectStmt.executeQuery(selectText);
• insertText = "INSERT INTO addresses VALUES
(1,'John','Smith')";
• Statement insertStmt = dbConnection.createStatement();
• int rowsInserted = insertStmt.executeUpdate(insertText);
June 21, 2017 23
Creating a Statement Object:Connection Interface
• PreparedStatement
• statement is pre-compiled and stored in a
PreparedStatement object. Can use this to efficiently
execute the statement multiple times
• allows IN parameters within the query
• referenced by number
• setXXX () methods used
• setXXX();
– pstmt.setString (1, "SCOTT");
• getXXX();
– System.out.println( rset.getString (1) );
• setNULL(); - don’t use nulls
June 21, 2017 24
Setting Parameters & Getting Fields
• Provides access to a table of data generated by executing a
Statement
• Table rows are retrieved in sequence via a cursor pointing
to the current row of data
• Some methods:
• next ()
• getXXX () methods
• wasNull ()—detect SQL NULL values
• close ()
June 21, 2017 25
ResultSet Interface
• ResultSet rset = stmt.executeQuery ("SELECT ename
FROM emp");
• executeUpdate
– insert, delete, update
• execute():
• while (rset.next())
System.out.println (rset.getString(1));
• This is standard JDBC syntax. The next() method returns
false when it reaches the end of the result set. The
employee names are materialized as JavaStrings.
June 21, 2017 26
Executing a Query and Returning the ResultSet Interface
• You must explicitly close the ResultSet and Statement
objects after you finish using them.
• rset.close();
• stmt.close();
• You must close your connection to the database once you
finish your work.
• conn.close();
June 21, 2017 27
Closing the ResultSet, Statement and Connection
void dispResultSet (ResultSet rs) throws SQLException
{
while (rs.next ()) {
System.out.print ("" + rs.getInt (1))
String firstName = rs.getString ("FIRST_NAME");
System.out.print (rs.wasNull () ? “[no first name]” :
firstName);
System.out.print (rs.getString ("LAST_NAME"));
System.out.println (rs.getDate (4));
}
rs.close ();
}
June 21, 2017 28
ResultSet Interface
• getMessage(): returns the error message associated with
the object that threw the exception
• printStackTrace(): prints this object name and its stacktrace
to the specified print stream
• This example uses both getMessage() and
printStackTrace() to return errors.
catch(SQLException e); {
System.out.println("exception: " + e.getMessage());
e.printStackTrace();
}
OR
Continued…
June 21, 2017 29
SQLException
catch (SQLException e) {
while(e != null) {
System.out.println(e.getMessage());
e = e.getNextException();
}
}
June 21, 2017 30
SQL Exception

Weitere ähnliche Inhalte

Was ist angesagt?

Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepRajiv Gupta
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introductionejlp12
 
Java EE 8 Recipes
Java EE 8 RecipesJava EE 8 Recipes
Java EE 8 RecipesJosh Juneau
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questionsArun Vasanth
 
Java questions with answers
Java questions with answersJava questions with answers
Java questions with answersKuntal Bhowmick
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutesArun Gupta
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicIMC Institute
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCIMC Institute
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&aFaruk Molla
 
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 AdvancedIMC Institute
 
Java EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJosh Juneau
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1Hitesh-Java
 
Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)Hamed Hatami
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interviewprashant patel
 

Was ist angesagt? (19)

Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by step
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
 
Java EE 8 Recipes
Java EE 8 RecipesJava EE 8 Recipes
Java EE 8 Recipes
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questions
 
Java questions with answers
Java questions with answersJava questions with answers
Java questions with answers
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVC
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
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 EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVC
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 

Andere mochten auch (13)

Web services engine
Web services engineWeb services engine
Web services engine
 
Ide benchmarking
Ide benchmarkingIde benchmarking
Ide benchmarking
 
Training
TrainingTraining
Training
 
Project excursion career_orientation
Project excursion career_orientationProject excursion career_orientation
Project excursion career_orientation
 
Digital marketing
Digital marketingDigital marketing
Digital marketing
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Build tool
Build toolBuild tool
Build tool
 
Ci
CiCi
Ci
 
Ejb
EjbEjb
Ejb
 
ETL
ETLETL
ETL
 
Visual basics
Visual basicsVisual basics
Visual basics
 
Design pattern
Design patternDesign pattern
Design pattern
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
 

Ă„hnlich wie Jdbc

Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptkingkolju
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.pptNaveenKumar648465
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12Hemo Chella
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivityarikazukito
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Modelkunj desai
 
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, 2004derek_clark_ashmore
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)Fad Zulkifli
 
java.pptx
java.pptxjava.pptx
java.pptxbfgd1
 

Ă„hnlich wie Jdbc (20)

Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Model
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
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
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
java.pptx
java.pptxjava.pptx
java.pptx
 
jdbc
jdbcjdbc
jdbc
 
Jdbc
JdbcJdbc
Jdbc
 

Mehr von Mallikarjuna G D

Mehr von Mallikarjuna G D (18)

Reactjs
ReactjsReactjs
Reactjs
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
CSS
CSSCSS
CSS
 
Angular 2.0
Angular  2.0Angular  2.0
Angular 2.0
 
Mmg logistics edu-final
Mmg  logistics edu-finalMmg  logistics edu-final
Mmg logistics edu-final
 
Interview preparation devops
Interview preparation devopsInterview preparation devops
Interview preparation devops
 
Interview preparation testing
Interview preparation testingInterview preparation testing
Interview preparation testing
 
Interview preparation data_science
Interview preparation data_scienceInterview preparation data_science
Interview preparation data_science
 
Interview preparation full_stack_java
Interview preparation full_stack_javaInterview preparation full_stack_java
Interview preparation full_stack_java
 
Enterprunership
EnterprunershipEnterprunership
Enterprunership
 
Core java
Core javaCore java
Core java
 
Type script
Type scriptType script
Type script
 
Git Overview
Git OverviewGit Overview
Git Overview
 
Jenkins
JenkinsJenkins
Jenkins
 
Hadoop
HadoopHadoop
Hadoop
 
Installer benchmarking
Installer benchmarkingInstaller benchmarking
Installer benchmarking
 
Sql implementations
Sql implementationsSql implementations
Sql implementations
 
Dao benchmark
Dao benchmarkDao benchmark
Dao benchmark
 

KĂĽrzlich hochgeladen

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

KĂĽrzlich hochgeladen (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

Jdbc

  • 1. June 21, 2017 www.snipe.co.in 1 Prepared :Snipe Team
  • 2. June 21, 2017 2 Java Database Connection (JDBC)
  • 3. June 21, 2017 3 JDBC • JDBC is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. • JDBC - is the Java object version of Microsoft ODBC. - defines Java class wrappers for SQL database access. - can access almost any database service. - JDBC drivers are available from almost any Java vendor. - java.sql.* package is now part of the Java core. - compliance means the drivers support SQL92. - must implement the java.sql.* classes. - must be thread safe.
  • 4. • JDBC Naming Convention. "jdbc:oracle:thin:@oracle-prod:1521:OPROD“ , "scott", "tiger” The first string is the URL for the database including the protocol (jdbc), the vendor (oracle), the driver (thin), the server (oracle-prod), the port number (1521), and a server instance (OPROD). Second is the Username. Third is the Password. • JDBC Classes – JDBC Core Interfaces – Java Language extensions – Java Utility Extensions – SQL Metadata Interfaces. June 21, 2017 4 JDBC
  • 5. • JDBC is a Java-based data access technology (Java Standard Edition platform) from Oracle Corporation. • Sun Microsystems released JDBC as part of JDK 1.1 on February 19, 1997.[1] It has since formed part of the Java Standard Edition. • The JDBC classes are contained in the Java package java.sql and javax.sql. • Starting with version 3.1, JDBC has been developed under the Java Community Process. JSR 54 specifies JDBC 3.0 (included in J2SE 1.4), JSR 114 specifies the JDBC Rowset additions, and JSR 221 is the specification of JDBC 4.0 (included in Java SE 6).[2] • The latest version, JDBC 4.1, is specified by a maintenance release of JSR 221[3] and is included in Java SE 7.[4] June 21, 2017 5 JDBC History
  • 6. • JDBC 2.0 – Support for data types, such as objects, arrays, and large objects (LOBs). This is handled through the standard java.sql package. – Support for standard features, such as result set enhancements and update batching. This is handled through standard objects, such as Connection,ResultSet, and PreparedStatement, under JDK 1.2.x and later. – Support for extended features, such as features of the JDBC 2.0 optional package, also known as the standard extension application programming interface (API), including data sources, connection pooling, and distributed transactions June 21, 2017 6 JDBC Example
  • 7. • JDBC 2.0 – Transaction Savepoints – Retrieval of Auto-Generated Keys – JDBC 3.0 LOB Interface Methods – Result Set Holdability • JDBC 4.0 – Wrapper Pattern Support – Enhanced Exception Hierarchy and SQLException – The RowId Data Type – LOB Creation – National Language Character Set Support • JDBC 4.1 – The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement – RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by your JDBC driver. June 21, 2017 7 JDBC Example
  • 8. • Classes – locate DBMS drivers - DriverManagerClass • locates the driver for DB you specify – establish connections • commit, rollback and the DB isolation level – submit SQL statements • 2 extensions – Prepared statement - precompile and execute – Callable statement - stored procedures – process result set • manipulate the cursor and get back results June 21, 2017 8 JDBC Core
  • 9. June 21, 2017 9 JDBC Drivers - JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server - Using JDBC drivers enable you to open database Connections and to interact with it by sending SQL or database commands then receiving results with Java
  • 10. June 21, 2017 10 Type 1 JDBC Drivers • Type 1 : This driver converts JDBC calls to ODBC calls through JDBC-ODBC Bridge driver which in turn converts to database calls. Client requires ODBC libraries. • a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.
  • 11. June 21, 2017 11 Type 2 JDBC Drivers • Type 2 : This driver converts JDBC calls to database specific native calls. Client requires database specific libraries. • In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor- specific driver must be installed on each client machine • E.g:- Oracle call Interface(OCI)
  • 12. June 21, 2017 12 Type 3 JDBC Drivers • Type 3 : This driver passes calls to proxy server through network protocol which in turn converts to database calls and passes through database specific protocol. Client doesn't require any driver. • In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server.
  • 13. June 21, 2017 13 Type 4 JDBC Drivers • Type 4 This driver directly calls database. Client doesn't require any driver. • In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.
  • 14. June 21, 2017 14 Benchmarking JDBC Drivers • Type 4 - Accessing one type of database, such as Oracle, Sybase, or MySQL. • Type 3 - Accessing Multiple types of database at the same time • Type 2 - In case 3 or 4 not available on your machine • Type 1 - Drivers are not considered for deployment, only for development and testing
  • 15. • Import the JDBC Package • Set useful static class variables for driver, DBMS URI, credentials, etc. • Register appropriate driver with the DriverManager class • Set connection Properties (typically credentials) • Invoke the Connection • Create SQL statement in a String • Invoke Statement on connection • Execute SQL statement via appropriate method on Statement object. Continued… June 21, 2017 15 Typical Steps
  • 16. • execute(...), executeQuery(...) for SELECT to receive ResultSet/s. • executeUpdate(...) for INS/DEL/UPD or DDLs, receive integer value indicating row count . • automatic commit, unless disabled, in which case an explicit COMMIT must be executed to save changes to database. • Check for Exceptions. • Process ResultSet • Close ResultSet and Statement • Unless multiple transactions, then redefine and reuse • Cycle for further operations • Close Connection June 21, 2017 16 Typical Steps
  • 17. • oracle.jdbc.driver (classes to support database access and updates in Oracle type formats) • Load the Oracle JDBC driver DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); or Class.forName ("oracle.jdbc.driver.OracleDriver"); • Connect to the database Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@learning", “root", “pwd"); June 21, 2017 17 Registering & Connecting:The DriverManager Class
  • 18. • Code for creating a connection using JDBC with Oracle try { // register the driver to connect to oracle DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // db_con is a connection object that lets us connect to the // database with specified URL/userid/password Connection db_con = DriverManager.getConnection ("jdbc:oracle:thin:@llama.its.monash.edu.au:1521:CSE 5200A", "studentid", "password"); System.out.println("Connection Success"); } catch(SQLException f ){ // gives error if the above did not succeed. System.out.println("Connection Failed. SQL Exception"); • } June 21, 2017 18 Sample Code
  • 19. • Code to retrieve data from the Database using the previously created JDBC Connection object. try { // statement object stmt created to execute queries using //db_con Statement stmt = db_con.createStatement(); // resultset is an object that holds the result of the query ResultSet rset = stmt.executeQuery ("SELECT * FROM authors"); // looping through the resultset object till end while (rset.next()){ // getString gets the string data in col 1 of result // and we would have rset.getInt(2) if col 2 was an integer System.out.println (rset.getString(1)); }June 21, 2017 19 Sample Code
  • 20. } catch(SQLException f) { // error handling for above System.out.println("Cannot retrieve data SQL Exception occured"); } June 21, 2017 20 Sample Code
  • 21. • Connection Interface – Session between application and database – Specified by location (URI) and credentials • Commit/Rollback – conn.commit(); – conn.rollback(); • Set Autocommit off – after connect but before any statement • conn.setAutoCommit (false); June 21, 2017 21 Transactions:The Connection Interface
  • 22. • Statement stmt = conn.createStatement (); • stmt.execute (“select empno from emp”); – no parameters • PreparedStatement pmst = conn.prepareStatement (“insert into emp (EMPNO, EMPNAME) values (?, ?)”); - setting and getting parameters in next slides. • pstmt.execute(); • selectText = "SELECT firstname,lastname FROM addresses"; Continued… June 21, 2017 22 Creating a Statement Object:Connection Interface
  • 23. • Statement selectStmt = dbConnection.createStatement(); • ResultSet result = selectStmt.executeQuery(selectText); • insertText = "INSERT INTO addresses VALUES (1,'John','Smith')"; • Statement insertStmt = dbConnection.createStatement(); • int rowsInserted = insertStmt.executeUpdate(insertText); June 21, 2017 23 Creating a Statement Object:Connection Interface
  • 24. • PreparedStatement • statement is pre-compiled and stored in a PreparedStatement object. Can use this to efficiently execute the statement multiple times • allows IN parameters within the query • referenced by number • setXXX () methods used • setXXX(); – pstmt.setString (1, "SCOTT"); • getXXX(); – System.out.println( rset.getString (1) ); • setNULL(); - don’t use nulls June 21, 2017 24 Setting Parameters & Getting Fields
  • 25. • Provides access to a table of data generated by executing a Statement • Table rows are retrieved in sequence via a cursor pointing to the current row of data • Some methods: • next () • getXXX () methods • wasNull ()—detect SQL NULL values • close () June 21, 2017 25 ResultSet Interface
  • 26. • ResultSet rset = stmt.executeQuery ("SELECT ename FROM emp"); • executeUpdate – insert, delete, update • execute(): • while (rset.next()) System.out.println (rset.getString(1)); • This is standard JDBC syntax. The next() method returns false when it reaches the end of the result set. The employee names are materialized as JavaStrings. June 21, 2017 26 Executing a Query and Returning the ResultSet Interface
  • 27. • You must explicitly close the ResultSet and Statement objects after you finish using them. • rset.close(); • stmt.close(); • You must close your connection to the database once you finish your work. • conn.close(); June 21, 2017 27 Closing the ResultSet, Statement and Connection
  • 28. void dispResultSet (ResultSet rs) throws SQLException { while (rs.next ()) { System.out.print ("" + rs.getInt (1)) String firstName = rs.getString ("FIRST_NAME"); System.out.print (rs.wasNull () ? “[no first name]” : firstName); System.out.print (rs.getString ("LAST_NAME")); System.out.println (rs.getDate (4)); } rs.close (); } June 21, 2017 28 ResultSet Interface
  • 29. • getMessage(): returns the error message associated with the object that threw the exception • printStackTrace(): prints this object name and its stacktrace to the specified print stream • This example uses both getMessage() and printStackTrace() to return errors. catch(SQLException e); { System.out.println("exception: " + e.getMessage()); e.printStackTrace(); } OR Continued… June 21, 2017 29 SQLException
  • 30. catch (SQLException e) { while(e != null) { System.out.println(e.getMessage()); e = e.getNextException(); } } June 21, 2017 30 SQL Exception