SlideShare a Scribd company logo
1 of 26
JDBC –
Java DataBase Connectivity
R.Lakshmi
Assistant Professor ,
Department of Information Technology
E.M.G.Yadava Women’s College,
Madura i-14
What is JDBC?
2
● “An API that lets you access virtually any tabular data
source from the Java programming language”
● JDBC DataAccessAPI – 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?
3
4
Basic steps to use
a database in Java
5
● 1.Establish a connection
● 2.Create JDBC Statements
● 3.Execute SQL Statements
● 4.GET ResultSet
● 5.Close connections
1. Establish a connection
6
● 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)
7
● Statement stmt = con.createStatement() ;
● Creates a Statement object for sending SQL statements
to the database
Executing SQL Statements
8
● 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");
}
Close connection
10
● stmt.close();
● con.close();
Transactions and JDBC
11
● 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
12
● 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?
13
Sample program
14
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)
15
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
16
JDBC 2 – Scrollable Result Set
17
…
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();
}
18
Metadata from DB
19
● 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
20
…
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) );
}
}
JDBC and beyond
22
● (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
23
// 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
24
● JDBC Data AccessAPI – JDBC Technology Homepage
● http://java.sun.com/products/jdbc/index.html
● JDBC DatabaseAccess – 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/
Thank You
JDBC
26
● JDBC Data AccessAPI – JDBC Technology Homepage
● http://java.sun.com/products/jdbc/index.html
● JDBC DatabaseAccess – 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

Doctrine 2 - Introduction
Doctrine 2 - IntroductionDoctrine 2 - Introduction
Doctrine 2 - IntroductionDiego Lewin
 
Oracle table lock modes
Oracle table lock modesOracle table lock modes
Oracle table lock modesFranck Pachot
 
Ip project work test your knowledge
Ip project work test your knowledgeIp project work test your knowledge
Ip project work test your knowledgeKïShørê Choudhary
 
Database security
Database securityDatabase security
Database securityJaved Khan
 
Conexcion java mysql
Conexcion java mysqlConexcion java mysql
Conexcion java mysqljbersosa
 
Doctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkDoctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkIllia Antypenko
 
Hadoop and Marklogic: Using the Genetic Algorithm to generate Source Code
Hadoop and Marklogic: Using the Genetic Algorithm to generate Source CodeHadoop and Marklogic: Using the Genetic Algorithm to generate Source Code
Hadoop and Marklogic: Using the Genetic Algorithm to generate Source Codejimfuller2009
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaEdureka!
 
XSLT 3.0 - new features
XSLT 3.0 - new featuresXSLT 3.0 - new features
XSLT 3.0 - new featuresJakub Malý
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
Sql interview-book
Sql interview-bookSql interview-book
Sql interview-bookVipul Wankar
 
Database Programming
Database ProgrammingDatabase Programming
Database ProgrammingHenry Osborne
 
statement interface
statement interface statement interface
statement interface khush_boo31
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatablephanleson
 

What's hot (20)

Doctrine 2 - Introduction
Doctrine 2 - IntroductionDoctrine 2 - Introduction
Doctrine 2 - Introduction
 
Jdbc
Jdbc Jdbc
Jdbc
 
Oracle table lock modes
Oracle table lock modesOracle table lock modes
Oracle table lock modes
 
Sql server
Sql serverSql server
Sql server
 
Ip project work test your knowledge
Ip project work test your knowledgeIp project work test your knowledge
Ip project work test your knowledge
 
Database security
Database securityDatabase security
Database security
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Conexcion java mysql
Conexcion java mysqlConexcion java mysql
Conexcion java mysql
 
Database programming
Database programmingDatabase programming
Database programming
 
Doctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkDoctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWork
 
Hadoop and Marklogic: Using the Genetic Algorithm to generate Source Code
Hadoop and Marklogic: Using the Genetic Algorithm to generate Source CodeHadoop and Marklogic: Using the Genetic Algorithm to generate Source Code
Hadoop and Marklogic: Using the Genetic Algorithm to generate Source Code
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | Edureka
 
XSLT 3.0 - new features
XSLT 3.0 - new featuresXSLT 3.0 - new features
XSLT 3.0 - new features
 
Struts by l n rao
Struts by l n raoStruts by l n rao
Struts by l n rao
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
Sql interview-book
Sql interview-bookSql interview-book
Sql interview-book
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
statement interface
statement interface statement interface
statement interface
 
Hibernate by l n rao
Hibernate by l n raoHibernate by l n rao
Hibernate by l n rao
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatable
 

Similar to Module 5 jdbc.ppt (20)

JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Database connect
Database connectDatabase connect
Database connect
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 

Recently uploaded

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
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
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
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
“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
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
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
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
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
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 

Recently uploaded (20)

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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
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
 
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 ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
“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...
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
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🔝
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
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
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 

Module 5 jdbc.ppt

  • 1. JDBC – Java DataBase Connectivity R.Lakshmi Assistant Professor , Department of Information Technology E.M.G.Yadava Women’s College, Madura i-14
  • 2. What is JDBC? 2 ● “An API that lets you access virtually any tabular data source from the Java programming language” ● JDBC DataAccessAPI – 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? 3
  • 4. 4
  • 5. Basic steps to use a database in Java 5 ● 1.Establish a connection ● 2.Create JDBC Statements ● 3.Execute SQL Statements ● 4.GET ResultSet ● 5.Close connections
  • 6. 1. Establish a connection 6 ● 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) 7 ● Statement stmt = con.createStatement() ; ● Creates a Statement object for sending SQL statements to the database
  • 8. Executing SQL Statements 8 ● 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"); }
  • 11. Transactions and JDBC 11 ● 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 12 ● 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? 13
  • 14. Sample program 14 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) 15 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 16
  • 17. JDBC 2 – Scrollable Result Set 17 … 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(); } 18
  • 19. Metadata from DB 19 ● 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 20 … 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. JDBC and beyond 22 ● (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 23 // 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 24 ● JDBC Data AccessAPI – JDBC Technology Homepage ● http://java.sun.com/products/jdbc/index.html ● JDBC DatabaseAccess – 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/
  • 26. JDBC 26 ● JDBC Data AccessAPI – JDBC Technology Homepage ● http://java.sun.com/products/jdbc/index.html ● JDBC DatabaseAccess – 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/