SlideShare a Scribd company logo
JDBC – Java DataBase Connectivity   CSE432 Object Oriented  Software Engineering
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
General Architecture What design pattern is implied in this architecture? What does it buy for us? Why is this architecture also multi-tiered?
 
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
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
2. Create JDBC statement(s) Statement stmt = con.createStatement() ;  Creates a Statement object for sending SQL statements to the database
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);
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 " ); }
Close connection stmt.close(); con.close();
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.
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
Another way to access database (JDBC-ODBC) What’s a bit different about this architecture? Why add yet  another layer?
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");
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);  } } }
Mapping types JDBC - Java
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 …
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 (); }
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.
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 ); …
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) +&quot;,&quot;); / / output resultset while ( rs.next() ) { for(int i=1; i < nCols; ++i) System.out.print( rs. getString( i) +&quot;,&quot;); System.out.println( rs. getString(nCols)  ); } }
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
SQLJ // SQLJ int n; #sql { INSERT INTO emp VALUES (:n)}; // vs. straight JDBC int n; Statement stmt = conn.prepareStatement (“INSERT INTO emp VALUES (?)”); stmt.setInt(1,n); stmt.execute (); stmt.close();
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 /
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 /

More Related Content

What's hot (20)

Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
kamal kotecha
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
Arati Gadgil
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
Dharani Kumar Madduri
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
Soham Sengupta
 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXB
Martin Grebac
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
JAXB
JAXBJAXB
JAXB
srinivasanjayakumar
 
JSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML BindingJSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML Binding
Heiko Scherrer
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Jaxb
JaxbJaxb
Jaxb
Manav Prasad
 
XML parsing using jaxb
XML parsing using jaxbXML parsing using jaxb
XML parsing using jaxb
Malintha Adikari
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
backdoor
 
22jdbc
22jdbc22jdbc
22jdbc
Adil Jafri
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
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
WebStackAcademy
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
Tuan Ngo
 
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
kamal kotecha
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXB
Martin Grebac
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
JSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML BindingJSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML Binding
Heiko Scherrer
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
backdoor
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
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
WebStackAcademy
 
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 

Viewers also liked (20)

theQuiz(7);
theQuiz(7);theQuiz(7);
theQuiz(7);
Ampersand
 
How I tracked silence - Danielle Roberts
How I tracked silence - Danielle Roberts How I tracked silence - Danielle Roberts
How I tracked silence - Danielle Roberts
Ernesto Ramirez
 
Baum1
Baum1Baum1
Baum1
dmolina87
 
Gasteizko irteera 2B SIEMM
Gasteizko irteera 2B SIEMMGasteizko irteera 2B SIEMM
Gasteizko irteera 2B SIEMM
arbelar
 
Evaluation 3
Evaluation 3Evaluation 3
Evaluation 3
nctcmedia12
 
Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...
Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...
Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...
Moite Pari
 
Compositional Slideshow
Compositional SlideshowCompositional Slideshow
Compositional Slideshow
erika6820
 
Geografia
GeografiaGeografia
Geografia
javier Soto
 
Твердотопливный напольный котел Buderus Logano G221-20
Твердотопливный напольный котел Buderus Logano G221-20 Твердотопливный напольный котел Buderus Logano G221-20
Твердотопливный напольный котел Buderus Logano G221-20
Al Maks
 
Patriot-PT-SB76
Patriot-PT-SB76Patriot-PT-SB76
Patriot-PT-SB76
Al Maks
 
Project 1 powerpoint
Project 1 powerpointProject 1 powerpoint
Project 1 powerpoint
Speckie91
 
สอนแต่งภาพ
สอนแต่งภาพสอนแต่งภาพ
สอนแต่งภาพ
Gufgif Sweetzii
 
USAID PEER Program
USAID PEER ProgramUSAID PEER Program
USAID PEER Program
stacywhittle
 
Cells
CellsCells
Cells
pugazhkurianc
 
Project 7.4.1
Project 7.4.1Project 7.4.1
Project 7.4.1
Rosa McCollum
 
The Spirituality Of Animals
The Spirituality Of AnimalsThe Spirituality Of Animals
The Spirituality Of Animals
docheart
 
Yaksha prasna questions of yaksha
Yaksha prasna   questions of yakshaYaksha prasna   questions of yaksha
Yaksha prasna questions of yaksha
BASKARAN P
 
紫荊書院.1&2
紫荊書院.1&2紫荊書院.1&2
紫荊書院.1&2
小翰 蔡小翰
 
Introduction Presentation
Introduction PresentationIntroduction Presentation
Introduction Presentation
wise1199
 
How I tracked silence - Danielle Roberts
How I tracked silence - Danielle Roberts How I tracked silence - Danielle Roberts
How I tracked silence - Danielle Roberts
Ernesto Ramirez
 
Gasteizko irteera 2B SIEMM
Gasteizko irteera 2B SIEMMGasteizko irteera 2B SIEMM
Gasteizko irteera 2B SIEMM
arbelar
 
Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...
Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...
Достъп до финансиране на малките и средни предприятия.Проблеми и нови възможн...
Moite Pari
 
Compositional Slideshow
Compositional SlideshowCompositional Slideshow
Compositional Slideshow
erika6820
 
Твердотопливный напольный котел Buderus Logano G221-20
Твердотопливный напольный котел Buderus Logano G221-20 Твердотопливный напольный котел Buderus Logano G221-20
Твердотопливный напольный котел Buderus Logano G221-20
Al Maks
 
Patriot-PT-SB76
Patriot-PT-SB76Patriot-PT-SB76
Patriot-PT-SB76
Al Maks
 
Project 1 powerpoint
Project 1 powerpointProject 1 powerpoint
Project 1 powerpoint
Speckie91
 
สอนแต่งภาพ
สอนแต่งภาพสอนแต่งภาพ
สอนแต่งภาพ
Gufgif Sweetzii
 
USAID PEER Program
USAID PEER ProgramUSAID PEER Program
USAID PEER Program
stacywhittle
 
The Spirituality Of Animals
The Spirituality Of AnimalsThe Spirituality Of Animals
The Spirituality Of Animals
docheart
 
Yaksha prasna questions of yaksha
Yaksha prasna   questions of yakshaYaksha prasna   questions of yaksha
Yaksha prasna questions of yaksha
BASKARAN P
 
Introduction Presentation
Introduction PresentationIntroduction Presentation
Introduction Presentation
wise1199
 

Similar to Jdbc (20)

Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
phanleson
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
manvibaunthiyal1
 
Jdbc
JdbcJdbc
Jdbc
lathasiva
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
DEEPIKA T
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
Information Technology
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
MrsRLakshmiIT
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
BG Java EE Course
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
leminhvuong
 
jdbc
jdbcjdbc
jdbc
vikram singh
 
JDBC
JDBCJDBC
JDBC
Balwinder Kumar
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
Fulvio Corno
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
Swapnil Kale
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
jitendral
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
Jdbc
JdbcJdbc
Jdbc
myrajendra
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRC
tepsum
 

Recently uploaded (20)

How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 

Jdbc

  • 1. 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(&quot;oracle.jdbc.driver.OracleDriver&quot;); What do you think this statement does, and how? Dynamically loads a driver class, for Oracle database Make the connection Connection con = DriverManager.getConnection( &quot;jdbc:oracle:thin:@oracle-prod:1521:OPROD&quot;, 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 = &quot; Create table Lehigh &quot; + &quot; (SSN Integer not null, Name VARCHAR(32), &quot; + &quot; Marks Integer) &quot; ; stmt. executeUpdate (createLehigh); //What does this statement do? String insertLehigh = &quot; Insert into Lehigh values “ + &quot; (123456789,abc,100) &quot; ; stmt. executeUpdate (insertLehigh);
  • 9. Get ResultSet String queryLehigh = &quot; select * from Lehigh &quot; ; ResultSet rs = Stmt. executeQuery (queryLehigh); //What does this statement do? while (rs.next()) { int ssn = rs.getInt( &quot; SSN &quot; ); String name = rs.getString( &quot; NAME &quot; ); int marks = rs.getInt( &quot; MARKS &quot; ); }
  • 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 (&quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;); //dynamic loading of driver String filename = &quot;c:/db1. mdb &quot;; //Location of an Access database String database = &quot;jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=&quot;; database += filename.trim() + &quot;;DriverID=22;READONLY=true}&quot;; //add on to end Connection con = DriverManager. getConnection ( database ,&quot;&quot;,&quot;&quot;); Statement s = con.createStatement(); s.execute(&quot; create table TEST12345 ( firstcolumn integer )&quot;); s.execute(&quot; insert into TEST12345 values(1)&quot;); s.execute(&quot; select firstcolumn from TEST12345&quot;);
  • 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(&quot;Data from column_name: &quot; + 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(&quot;ERROR: &quot; + err); } } }
  • 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 = &quot; 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) +&quot;,&quot;); / / output resultset while ( rs.next() ) { for(int i=1; i < nCols; ++i) System.out.print( rs. getString( i) +&quot;,&quot;); 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
  • 23. SQLJ // SQLJ int n; #sql { INSERT INTO emp VALUES (:n)}; // vs. straight JDBC int n; Statement stmt = conn.prepareStatement (“INSERT INTO emp VALUES (?)”); stmt.setInt(1,n); stmt.execute (); stmt.close();
  • 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 /