SlideShare una empresa de Scribd logo
1 de 24
JDBC – 
Java DataBase Connectivity 
CSE432 
Object Oriented 
Software Engineering
2 
What is JDBC? 
 “An API that lets you access virtually any tabular data 
source from the Java programming language” 
 JDBC Data Access API – JDBC Technology Homepage 
 What’s an API? 
 See J2SE documentation 
 What’s a tabular data source? 
 “… access virtually any data source, from relational 
databases to spreadsheets and flat files.” 
 JDBC Documentation 
 We’ll focus on accessing Oracle databases
3 
General Architecture 
 What design pattern is 
implied in this 
architecture? 
 What does it buy for us? 
 Why is this architecture 
also multi-tiered?
4
5 
Basic steps to use 
a database in Java 
 1.Establish a connection 
 2.Create JDBC Statements 
 3.Execute SQL Statements 
 4.GET ResultSet 
 5.Close connections
6 
1. Establish a connection 
 import java.sql.*; 
 Load the vendor specific driver 
 Class.forName("oracle.jdbc.driver.OracleDriver"); 
 What do you think this statement does, and how? 
 Dynamically loads a driver class, for Oracle database 
 Make the connection 
 Connection con = DriverManager.getConnection( 
"jdbc:oracle:thin:@oracle-prod:1521:OPROD", username, 
passwd); 
 What do you think this statement does? 
 Establishes connection to database by obtaining 
a Connection object
7 
2. Create JDBC statement(s) 
 Statement stmt = con.createStatement() ; 
 Creates a Statement object for sending SQL statements 
to the database
8 
Executing SQL Statements 
 String createLehigh = "Create table Lehigh " + 
"(SSN Integer not null, Name VARCHAR(32), " 
+ "Marks Integer)"; 
stmt.executeUpdate(createLehigh); 
//What does this statement do? 
 String insertLehigh = "Insert into Lehigh values“ 
+ "(123456789,abc,100)"; 
stmt.executeUpdate(insertLehigh);
9 
Get ResultSet 
String queryLehigh = "select * from Lehigh"; 
ResultSet rs = Stmt.executeQuery(queryLehigh); 
//What does this statement do? 
while (rs.next()) { 
int ssn = rs.getInt("SSN"); 
String name = rs.getString("NAME"); 
int marks = rs.getInt("MARKS"); 
}
10 
Close connection 
 stmt.close(); 
 con.close();
11 
Transactions and JDBC 
 JDBC allows SQL statements to be grouped together into a 
single transaction 
 Transaction control is performed by the Connection object, 
default mode is auto-commit, I.e., each sql statement is treated 
as a transaction 
 We can turn off the auto-commit mode with 
con.setAutoCommit(false); 
 And turn it back on with con.setAutoCommit(true); 
 Once auto-commit is off, no SQL statement will be committed 
until an explicit is invoked con.commit(); 
 At this point all changes done by the SQL statements will be 
made permanent in the database.
12 
Handling Errors with 
Exceptions 
 Programs should recover and leave the database in 
a consistent state. 
 If a statement in the try block throws an exception or 
warning, it can be caught in one of the 
corresponding catch statements 
 How might a finally {…} block be helpful here? 
 E.g., you could rollback your transaction in a 
catch { …} block or close database connection and 
free database related resources in finally {…} block
13 
Another way to access database 
(JDBC-ODBC) 
What’s a bit different 
about this 
architecture? 
Why add yet 
another layer?
14 
Sample program 
import java.sql.*; 
class Test { 
public static void main(String[] args) { 
try { 
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //dynamic loading of driver 
String filename = "c:/db1.mdb"; //Location of an Access database 
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; 
database+= filename.trim() + ";DriverID=22;READONLY=true}"; //add on to end 
Connection con = DriverManager.getConnection( database ,"",""); 
Statement s = con.createStatement(); 
s.execute("create table TEST12345 ( firstcolumn integer )"); 
s.execute("insert into TEST12345 values(1)"); 
s.execute("select firstcolumn from TEST12345");
15 
Sample program(cont) 
ResultSet rs = s.getResultSet(); 
if (rs != null) // if rs == null, then there is no ResultSet to view 
while ( rs.next() ) // this will step through our data row-by-row 
{ /* the next line will get the first column in our current row's ResultSet 
as a String ( getString( columnNumber) ) and output it to the screen */ 
System.out.println("Data from column_name: " + rs.getString(1) ); 
} 
s.close(); // close Statement to let the database know we're done with it 
con.close(); //close connection 
} 
catch (Exception err) { System.out.println("ERROR: " + err); } 
} 
}
16 
Mapping types JDBC - Java
17 
JDBC 2 – Scrollable Result Set 
… 
Statement stmt = 
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
ResultSet.CONCUR_READ_ONLY); 
String query = “select students from class where type=‘not sleeping’ “; 
ResultSet rs = stmt.executeQuery( query ); 
rs.previous(); / / go back in the RS (not possible in JDBC 1…) 
rs.relative(-5); / / go 5 records back 
rs.relative(7); / / go 7 records forward 
rs.absolute(100); / / go to 100th record 
…
18 
JDBC 2 – Updateable ResultSet 
… 
Statement stmt = 
con.createStatement(ResultSet.TYPE_FORWARD_ONLY, 
ResultSet.CONCUR_UPDATABLE); 
String query = " select students, grade from class 
where type=‘really listening this presentation’ “; 
ResultSet rs = stmt.executeQuery( query ); 
… 
while ( rs.next() ) 
{ 
int grade = rs.getInt(“grade”); 
rs.updateInt(“grade”, grade+10); 
rs.updateRow(); 
}
19 
Metadata from DB 
 A Connection's database is able 
to provide schema information 
describing its tables, 
its supported SQL grammar, 
its stored procedures 
the capabilities of this connection, and so on 
 What is a stored procedure? 
 Group of SQL statements that form a logical unit 
and perform a particular task 
This information is made available through 
a DatabaseMetaData object.
20 
Metadata from DB - example 
… 
Connection con = …. ; 
DatabaseMetaData dbmd = con.getMetaData(); 
String catalog = null; 
String schema = null; 
String table = “sys%”; 
String[ ] types = null; 
ResultSet rs = 
dbmd.getTables(catalog , schema , table , types ); 
…
21 
JDBC – Metadata from RS 
public static void printRS(ResultSet rs) throws SQLException 
{ 
ResultSetMetaData md = rs.getMetaData(); 
// get number of columns 
int nCols = md.getColumnCount(); 
// print column names 
for(int i=1; i < nCols; ++i) 
System.out.print( md.getColumnName( i)+","); 
/ / output resultset 
while ( rs.next() ) 
{ for(int i=1; i < nCols; ++i) 
System.out.print( rs.getString( i)+","); 
System.out.println( rs.getString(nCols) ); 
} 
}
22 
JDBC and beyond 
 (JNDI) Java Naming and Directory Interface 
 API for network-wide sharing of information about users, 
machines, networks, services, and applications 
 Preserves Java’s object model 
 (JDO) Java Data Object 
 Models persistence of objects, using RDBMS as repository 
 Save, load objects from RDBMS 
 (SQLJ) Embedded SQL in Java 
 Standardized and optimized by Sybase, Oracle and IBM 
 Java extended with directives: # sql 
 SQL routines can invoke Java methods 
 Maps SQL types to Java classes
24 
JDBC references 
 JDBC Data Access API – JDBC Technology Homepage 
 http://java.sun.com/products/jdbc/index.html 
 JDBC Database Access – The Java Tutorial 
 http://java.sun.com/docs/books/tutorial/jdbc/index.html 
 JDBC Documentation 
 http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html 
 java.sql package 
 http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html 
 JDBC Technology Guide: Getting Started 
 http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html 
 JDBC API Tutorial and Reference (book) 
 http://java.sun.com/docs/books/jdbc/
25 
JDBC 
 JDBC Data Access API – JDBC Technology Homepage 
 http://java.sun.com/products/jdbc/index.html 
 JDBC Database Access – The Java Tutorial 
 http://java.sun.com/docs/books/tutorial/jdbc/index.html 
 JDBC Documentation 
 http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html 
 java.sql package 
 http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html 
 JDBC Technology Guide: Getting Started 
 http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html 
 JDBC API Tutorial and Reference (book) 
 http://java.sun.com/docs/books/jdbc/

Más contenido relacionado

La actualidad más candente

Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationDave Stokes
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLJohn David Duncan
 
Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopSvetlin Nakov
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBCWebStackAcademy
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196Mahmoud Samir Fayed
 
Doctrine 2 - Introduction
Doctrine 2 - IntroductionDoctrine 2 - Introduction
Doctrine 2 - IntroductionDiego Lewin
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Marco Tusa
 
The Ring programming language version 1.5.1 book - Part 26 of 180
The Ring programming language version 1.5.1 book - Part 26 of 180The Ring programming language version 1.5.1 book - Part 26 of 180
The Ring programming language version 1.5.1 book - Part 26 of 180Mahmoud Samir Fayed
 

La actualidad más candente (20)

spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Jdbc
JdbcJdbc
Jdbc
 
iBATIS
iBATISiBATIS
iBATIS
 
22jdbc
22jdbc22jdbc
22jdbc
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache Hadoop
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
Database programming
Database programmingDatabase programming
Database programming
 
The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181
 
The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202
 
Sql server
Sql serverSql server
Sql server
 
The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184
 
The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196
 
Doctrine 2 - Introduction
Doctrine 2 - IntroductionDoctrine 2 - Introduction
Doctrine 2 - Introduction
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
 
The Ring programming language version 1.5.1 book - Part 26 of 180
The Ring programming language version 1.5.1 book - Part 26 of 180The Ring programming language version 1.5.1 book - Part 26 of 180
The Ring programming language version 1.5.1 book - Part 26 of 180
 

Similar a Jdbc (20)

JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
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 Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Último (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Jdbc

  • 1. JDBC – Java DataBase Connectivity CSE432 Object Oriented Software Engineering
  • 2. 2 What is JDBC?  “An API that lets you access virtually any tabular data source from the Java programming language”  JDBC Data Access API – JDBC Technology Homepage  What’s an API?  See J2SE documentation  What’s a tabular data source?  “… access virtually any data source, from relational databases to spreadsheets and flat files.”  JDBC Documentation  We’ll focus on accessing Oracle databases
  • 3. 3 General Architecture  What design pattern is implied in this architecture?  What does it buy for us?  Why is this architecture also multi-tiered?
  • 4. 4
  • 5. 5 Basic steps to use a database in Java  1.Establish a connection  2.Create JDBC Statements  3.Execute SQL Statements  4.GET ResultSet  5.Close connections
  • 6. 6 1. Establish a connection  import java.sql.*;  Load the vendor specific driver  Class.forName("oracle.jdbc.driver.OracleDriver");  What do you think this statement does, and how?  Dynamically loads a driver class, for Oracle database  Make the connection  Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@oracle-prod:1521:OPROD", username, passwd);  What do you think this statement does?  Establishes connection to database by obtaining a Connection object
  • 7. 7 2. Create JDBC statement(s)  Statement stmt = con.createStatement() ;  Creates a Statement object for sending SQL statements to the database
  • 8. 8 Executing SQL Statements  String createLehigh = "Create table Lehigh " + "(SSN Integer not null, Name VARCHAR(32), " + "Marks Integer)"; stmt.executeUpdate(createLehigh); //What does this statement do?  String insertLehigh = "Insert into Lehigh values“ + "(123456789,abc,100)"; stmt.executeUpdate(insertLehigh);
  • 9. 9 Get ResultSet String queryLehigh = "select * from Lehigh"; ResultSet rs = Stmt.executeQuery(queryLehigh); //What does this statement do? while (rs.next()) { int ssn = rs.getInt("SSN"); String name = rs.getString("NAME"); int marks = rs.getInt("MARKS"); }
  • 10. 10 Close connection  stmt.close();  con.close();
  • 11. 11 Transactions and JDBC  JDBC allows SQL statements to be grouped together into a single transaction  Transaction control is performed by the Connection object, default mode is auto-commit, I.e., each sql statement is treated as a transaction  We can turn off the auto-commit mode with con.setAutoCommit(false);  And turn it back on with con.setAutoCommit(true);  Once auto-commit is off, no SQL statement will be committed until an explicit is invoked con.commit();  At this point all changes done by the SQL statements will be made permanent in the database.
  • 12. 12 Handling Errors with Exceptions  Programs should recover and leave the database in a consistent state.  If a statement in the try block throws an exception or warning, it can be caught in one of the corresponding catch statements  How might a finally {…} block be helpful here?  E.g., you could rollback your transaction in a catch { …} block or close database connection and free database related resources in finally {…} block
  • 13. 13 Another way to access database (JDBC-ODBC) What’s a bit different about this architecture? Why add yet another layer?
  • 14. 14 Sample program import java.sql.*; class Test { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //dynamic loading of driver String filename = "c:/db1.mdb"; //Location of an Access database String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; database+= filename.trim() + ";DriverID=22;READONLY=true}"; //add on to end Connection con = DriverManager.getConnection( database ,"",""); Statement s = con.createStatement(); s.execute("create table TEST12345 ( firstcolumn integer )"); s.execute("insert into TEST12345 values(1)"); s.execute("select firstcolumn from TEST12345");
  • 15. 15 Sample program(cont) ResultSet rs = s.getResultSet(); if (rs != null) // if rs == null, then there is no ResultSet to view while ( rs.next() ) // this will step through our data row-by-row { /* the next line will get the first column in our current row's ResultSet as a String ( getString( columnNumber) ) and output it to the screen */ System.out.println("Data from column_name: " + rs.getString(1) ); } s.close(); // close Statement to let the database know we're done with it con.close(); //close connection } catch (Exception err) { System.out.println("ERROR: " + err); } } }
  • 16. 16 Mapping types JDBC - Java
  • 17. 17 JDBC 2 – Scrollable Result Set … Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String query = “select students from class where type=‘not sleeping’ “; ResultSet rs = stmt.executeQuery( query ); rs.previous(); / / go back in the RS (not possible in JDBC 1…) rs.relative(-5); / / go 5 records back rs.relative(7); / / go 7 records forward rs.absolute(100); / / go to 100th record …
  • 18. 18 JDBC 2 – Updateable ResultSet … Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); String query = " select students, grade from class where type=‘really listening this presentation’ “; ResultSet rs = stmt.executeQuery( query ); … while ( rs.next() ) { int grade = rs.getInt(“grade”); rs.updateInt(“grade”, grade+10); rs.updateRow(); }
  • 19. 19 Metadata from DB  A Connection's database is able to provide schema information describing its tables, its supported SQL grammar, its stored procedures the capabilities of this connection, and so on  What is a stored procedure?  Group of SQL statements that form a logical unit and perform a particular task This information is made available through a DatabaseMetaData object.
  • 20. 20 Metadata from DB - example … Connection con = …. ; DatabaseMetaData dbmd = con.getMetaData(); String catalog = null; String schema = null; String table = “sys%”; String[ ] types = null; ResultSet rs = dbmd.getTables(catalog , schema , table , types ); …
  • 21. 21 JDBC – Metadata from RS public static void printRS(ResultSet rs) throws SQLException { ResultSetMetaData md = rs.getMetaData(); // get number of columns int nCols = md.getColumnCount(); // print column names for(int i=1; i < nCols; ++i) System.out.print( md.getColumnName( i)+","); / / output resultset while ( rs.next() ) { for(int i=1; i < nCols; ++i) System.out.print( rs.getString( i)+","); System.out.println( rs.getString(nCols) ); } }
  • 22. 22 JDBC and beyond  (JNDI) Java Naming and Directory Interface  API for network-wide sharing of information about users, machines, networks, services, and applications  Preserves Java’s object model  (JDO) Java Data Object  Models persistence of objects, using RDBMS as repository  Save, load objects from RDBMS  (SQLJ) Embedded SQL in Java  Standardized and optimized by Sybase, Oracle and IBM  Java extended with directives: # sql  SQL routines can invoke Java methods  Maps SQL types to Java classes
  • 23. 24 JDBC references  JDBC Data Access API – JDBC Technology Homepage  http://java.sun.com/products/jdbc/index.html  JDBC Database Access – The Java Tutorial  http://java.sun.com/docs/books/tutorial/jdbc/index.html  JDBC Documentation  http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html  java.sql package  http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html  JDBC Technology Guide: Getting Started  http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html  JDBC API Tutorial and Reference (book)  http://java.sun.com/docs/books/jdbc/
  • 24. 25 JDBC  JDBC Data Access API – JDBC Technology Homepage  http://java.sun.com/products/jdbc/index.html  JDBC Database Access – The Java Tutorial  http://java.sun.com/docs/books/tutorial/jdbc/index.html  JDBC Documentation  http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html  java.sql package  http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html  JDBC Technology Guide: Getting Started  http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html  JDBC API Tutorial and Reference (book)  http://java.sun.com/docs/books/jdbc/