SlideShare a Scribd company logo
JDBC –
Java DataBase Connectivity
Sasidhar
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
 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
Advantages
1. Simplified Enterprise Development:
By integrating with java JDBC code becomes very less. It is
simple to install and maintain. Easy to write JDBC program
2. Zero Configuration for Network computers:
No configuration is required. We require a suitable driver to
connect to the database. It may be a bridge driver or a driver
written in java.
3. Full Access to Metadata: JDBC API includes classes
and interfaces to obtain metadata.
4. No Installation:
5. Database connection identified by URL: connectivity
through DataSource object. Data source objects can provide
connection pooling and transaction management.
6. Included in the J2EE platform: As JDBC API is needed in
enterprise applications to connect to databases, it is included in
the java2.0 Enterprise Edition.
Advantages
JDBC API
 It contains two main interfaces.
1. An API for application writers and
2. A lower level driver API for driver writers.
The set of classes that implement these lower level API
interfaces for a particular database engine is called a
JDBC driver
A program needs a specific driver to connect to a specific
database
Popular Drivers
Driver RDBMS
Oracle.jdbc.driver.OracleDriver ORACLE
Com.mysql.jdbc.Driver MySQL
Com.sybase.jdbc.SybDriver Sybase
Com.microsoft.jdbc.sqlserver.SQLServer
Driver
SQL Server
Com.ibm.db2.jdbc.net.DB2Driver DB2
Org.hsqldbJdbcDriver HSQL DB
Types of Drivers
1. Type1 ( JDBC-ODBC bridge + ODBC driver)
2. Type2 (partial JDBC driver)
3. Type3 (pure java JDBC driver for database
middleware)
4. Type4 (pure Java JDBC driver with a direct
database connection)
Type 1 driver
 Allows an application to access database through an
intermediate ODBC driver.
 It provides a gateway to the ODBC API
Disadvantages:
1. ODBC binary code must be loaded on each client
machine that uses this driver, limiting the usefulness of
this type of driver for the internet
2. Translation overhead between JDBC and ODBC
3. User is limited by the functionality of the underlying ODBC
driver.
4. Doesn’t support all the features of java.
5. It only works under the Microsoft windows and Sun
Solaris operating systems.
Type 2, 3,4 Drivers
 Type 2-driver converts JDBC calls into client API calls for
the DBMS. Also communicates directly with the database
server. This driver offers better performance than type 1
driver.
 Type-3 driver is completely implemented in java, hence it
is a pure java JDBC driver. It translates JDBC calls into
the middleware vendors’ protocol and translated to a
DBMS protocol by a middleware server.
 Type-4 drivers talks directly to the database using java
sockets. These type of drivers are completely
implemented in java to achieve platform independence
and eliminate deployment issues. This type of drivers
comes from the database vendor.
10
General Architecture
 What design pattern is
implied in this
architecture?
 What does it buy for us?
 Why is this architecture
also multi-tiered?
11
12
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
13
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:@oracl
e-prod:1521:OPROD", username, passwd);
 What do you think this statement does?
 Establishes connection to database by obtaining
a Connection object
14
2. Create JDBC statement(s)
 Statement stmt = con.createStatement() ;
 Creates a Statement object for sending SQL statements
to the database
15
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);
16
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");
}
17
Close connection
 stmt.close();
 con.close();
18
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.
19
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
20
Another way to access database
(JDBC-ODBC)
What’s a bit different
about this
architecture?
Why add yet
another layer?
21
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");
22
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); }
}
}
23
Mapping types JDBC - Java
24
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
…
25
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();
}
26
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.
27
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 );
…
28
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) );
}
}
29
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
JDBC API
PreparedStatement
• Represents a precompiled SQL statement
• Can be used to efficiently execute
statement multiple times
• Somewhat flexible – can create new ones
as needed
A prepared statement can contain variables that
you supply each time you execute the statement.
Optimized Statements
 Prepared Statements
 SQL calls that you make again and again
 allows driver to optimize (compile) queries
 created with Connection.prepareStatement()
 Stored Procedures
 written in DB-specific language
 stored inside database
 accessed with Connection.prepareCall()
Prepared Statements Performance
 Prepared Statements are more
efficient than Statements when
executing SQL statements multiple times
and with different parameter values.
Prepared Statements
 PreparedStatements execute more
efficiently than Statement objects
 PreparedStatements can specify
parameters
PreparedStatements
 PreparedStatement to locate all book titles for
an author with a specific last name and first name,
and to execute that query for several authors:
 PreparedStatement authorBooks =
connection.prepareStatement(
"SELECT lastName, firstName, title " +
"FROM authors INNER JOIN authorISBN " +
"ON authors.authorID=authorISBN.authorID "
+
"INNER JOIN titles " +
"ON authorISBN.isbn=titles.isbn " +
"WHERE lastName = ? AND firstName = ?" );
 Question marks (?) are placeholders for values that
will be passed as part of the query to the database
PreparedStatements
 Program must specify the parameter values by
using the PreparedStatement interface’s set
methods.
 For the preceding query, both parameters are
strings that can be set with PreparedStatement
method setString as follows:
authorBooks.setString( 1, "Deitel" );
authorBooks.setString( 2, "Paul" );
 setString automatically escapes String
parameter values as necessary (e.g., the quote in
the name O’Brien)
Prepared Statement Example
PreparedStatement updateSales;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME like ?";
updateSales = con.prepareStatement(updateString);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast",
"Espresso","Colombian_Decaf","French_Roast_Decaf"};
int len = coffees.length;
for(int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
}
JDBC Class Diagram
The Callable Statement Object
 A Callable Statement object holds parameters
for calling stored procedures.
 A callable statement can contain variables that
you supply each time you execute the call.
 When the stored procedure returns, computed
values (if any) are retrieved through the
Callable Statement object.
JDBC API
java.sql.CallableStatement
• Used to execute SQL stored procedures.
• Same syntax as PreparedStatement.
• Least flexible.
• Most optimized DB call.
CallableStatement cstmt =
conn.prepareCall("{call " +
ADDITEM + "(?,?,?)}");
cstmt.registerOutParameter(2,Types.INTEGER);
cStmt.registerOutParameter(3,Types.DOUBLE);
How to Create a Callable
Statement
 Register the driver and create the database
connection.
 Create the callable statement, identifying
variables with a question mark (?).
How to Execute
a callable
Statement
How to Execute
a callable
Statement
cstmt.setXXX(index, value);
cstmt.execute(statement);
var = cstmt.getXXX(index);
Database access through JSP
Three-Tier Architecture
Oracle
DB Server
Apache Tomcat
App Server
Microsoft
Internet
Explorer
HTML
Tuples
HTTP
Requests
JDBC
Requests
Java Server
Pages (JSPs)
Located
@ DBLab
Located
@ Your PC
Located
@ Any PC
import java.sql.*;  
class JdbcTest {
public static void main (String args []) throws SQLException {
// Load Oracle driver
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
// Connect to the local database
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@myhost:1521:ORCL","scott", "tiger");
JDBC
// Query the student names
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT name FROM Student");
// Print the name out
//name is the 2nd
attribute of Student
while (rset.next ())
System.out.println (rset.getString (2)); 
//close the result set, statement, and the connection
rset.close();
stmt.close();
conn.close();
JSP Syntax
 Comment
 <%-- Comment --%>
 Expression
 <%= java expression %>
 Scriplet
 <% java code fragment %>
 Include
 <jsp:include page="relativeURL" />
Entry Form - First Attempt
<b>Data Entry Menu</b>
<ul>
<li>
<a href="courses.jsp">Courses<a>
</li>
<li>
<a href="classes.jsp">Classes<a>
</li>
<li>
<a href="students.jsp">Students<a>
</li>
</ul>
Menu HTML Code
Entry Form - First Attempt
<html>
<body>
<table>
<tr>
<td>
<jsp:include page="menu.html" />
</td>
<td>
Open connection code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
JSP Code
Entry Form - First Attempt
<%-- Set the scripting language to java and --%>
<%-- import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>
<%
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
// Make a connection to the Oracle datasource
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@feast.ucsd.edu:1521:source",
“user", “pass");
%>
Open Connectivity Code
Entry Form - First Attempt
<%
// Create the statement
Statement statement = conn.createStatement();
// Use the statement to SELECT the student attributes
// FROM the Student table.
ResultSet rs = statement.executeQuery
("SELECT * FROM Student");
%>
Statement Code
Entry Form - First Attempt
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Presentation Code
Entry Form - First Attempt
Entry Form - First Attempt
<tr>
<%-- Get the SSN, which is a number --%>
<td><%= rs.getInt("SSN") %></td>
<%-- Get the ID --%>
<td><%= rs.getString("ID") %></td>
<%-- Get the FIRSTNAME --%>
<td><%= rs.getString("FIRSTNAME") %></td>
<%-- Get the LASTNAME --%>
<td><%= rs.getString("LASTNAME") %></td>
<%-- Get the COLLEGE --%>
<td><%= rs.getString("COLLEGE") %></td>
</tr>
Iteration Code
Entry Form - First Attempt
<%
// Close the ResultSet
rs.close();
// Close the Statement
statement.close();
// Close the Connection
conn.close();
} catch (SQLException sqle) {
out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
%>
Close Connectivity Code
Entry Form - Second Attempt
Entry Form - Second Attempt
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
JSP Code
Entry Form - Second Attempt
// Check if an insertion is requested
String action = request.getParameter("action");
if (action != null && action.equals("insert")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// INSERT the student attrs INTO the Student table.
PreparedStatement pstmt = conn.prepareStatement(
("INSERT INTO Student VALUES (?, ?, ?, ?, ?)"));
pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN")));
pstmt.setString(2, request.getParameter("ID"));
…
pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
}
Insertion Code
Entry Form - Second Attempt
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Presentation Code
Entry Form - Second Attempt
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="insert" name="action">
<th><input value="" name="SSN" size="10"></th>
<th><input value="" name="ID" size="10"></th>
<th><input value="" name="FIRSTNAME" size="15"></th>
<th><input value="" name="LASTNAME" size="15"></th>
<th><input value="" name="COLLEGE" size="15"></th>
<th><input type="submit" value="Insert"></th>
</form>
</tr>
Insert Form Code
Entry Form - Third Attempt
Entry Form - Third Attempt
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Update Code
Delete Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
JSP Code
Entry Form - Third Attempt
// Check if an update is requested
if (action != null && action.equals("update")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// UPDATE the student attributes in the Student table.
PreparedStatement pstatement = conn.prepareStatement(
"UPDATE Student SET ID = ?, FIRSTNAME = ?, " +
"LASTNAME = ?, COLLEGE = ? WHERE SSN = ?");
pstatement.setString(1, request.getParameter("ID"));
pstatement.setString(2, request.getParameter("FIRSTNAME"));
…
int rowCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Update Code
Entry Form - Third Attempt
// Check if a delete is requested
if (action != null && action.equals("delete")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// DELETE the student FROM the Student table.
PreparedStatement pstmt = conn.prepareStatement(
"DELETE FROM Student WHERE SSN = ?");
pstmt.setInt(1,
Integer.parseInt(request.getParameter("SSN")));
int rowCount = pstmt.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Delete Code
Entry Form - Third Attempt
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Presentation Code
Entry Form - Third Attempt
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="update" name="action">
<td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td>
<td><input value="<%= rs.getString("ID") %>" name="ID"></td>
…
<td><input type="submit" value="Update"></td>
</form>
<form action="students2.jsp" method="get">
<input type="hidden" value="delete" name="action">
<input type="hidden" value="<%= rs.getInt("SSN") %>" name="SSN">
<td><input type="submit" value="Delete"></td>
</form>
</tr>
Iteration Code

More Related Content

What's hot

Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
Ambarish Rai
 
Jdbc
JdbcJdbc
Jdbc
Indu Lata
 
Jdbc
JdbcJdbc
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
Sandeep Rawat
 
Jdbc
JdbcJdbc
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
Rohit Jain
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
Fulvio Corno
 
Jdbc
JdbcJdbc
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
KV(AFS) Utarlai, Barmer (Rajasthan)
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
Dharita Chokshi
 
Jdbc
JdbcJdbc
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
Adil Mehmoood
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
varun arora
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
Information Technology
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
Mindfire Solutions
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
Niit Care
 

What's hot (19)

Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Jdbc
JdbcJdbc
Jdbc
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Jdbc
JdbcJdbc
Jdbc
 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
Jdbc
JdbcJdbc
Jdbc
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 

Similar to Jdbc sasidhar

Jdbc
JdbcJdbc
Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
ChagantiSahith
 
JDBC
JDBCJDBC
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
backdoor
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
manvibaunthiyal1
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
TabassumMaktum
 
JDBC
JDBCJDBC
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
Tuan Ngo
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
Rakesh Kumar Ray
 
Prashanthi
PrashanthiPrashanthi
Java jdbc
Java jdbcJava jdbc
Java jdbc
Arati Gadgil
 
java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)
Daroko blog(www.professionalbloggertricks.com)
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
DEEPIKA T
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
rajan981
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
Fulvio Corno
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc
JdbcJdbc
Jdbc
lathasiva
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
Hemo Chella
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 

Similar to Jdbc sasidhar (20)

Jdbc
JdbcJdbc
Jdbc
 
Lecture17
Lecture17Lecture17
Lecture17
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC
JDBCJDBC
JDBC
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
JDBC
JDBCJDBC
JDBC
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 

More from Sasidhar Kothuru

Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
Sasidhar Kothuru
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
Sasidhar Kothuru
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
Sasidhar Kothuru
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Spsl by sasidhar 3 unit
Spsl by sasidhar  3 unitSpsl by sasidhar  3 unit
Spsl by sasidhar 3 unit
Sasidhar Kothuru
 
Spsl unit1
Spsl   unit1Spsl   unit1
Spsl unit1
Sasidhar Kothuru
 
Spsl II unit
Spsl   II unitSpsl   II unit
Spsl II unit
Sasidhar Kothuru
 
Servlets
ServletsServlets
Servers names
Servers namesServers names
Servers names
Sasidhar Kothuru
 
Servers names
Servers namesServers names
Servers names
Sasidhar Kothuru
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
Sasidhar Kothuru
 
Xml quiz 3 unit
Xml quiz   3 unitXml quiz   3 unit
Xml quiz 3 unit
Sasidhar Kothuru
 
Web technologies quiz questions - unit1,2
Web technologies quiz questions  - unit1,2Web technologies quiz questions  - unit1,2
Web technologies quiz questions - unit1,2
Sasidhar Kothuru
 
Web technologies 4th unit quiz
Web technologies 4th unit quizWeb technologies 4th unit quiz
Web technologies 4th unit quiz
Sasidhar Kothuru
 
Xml quiz 3 unit
Xml quiz   3 unitXml quiz   3 unit
Xml quiz 3 unit
Sasidhar Kothuru
 
Web technologies quiz questions - unit1,2
Web technologies quiz questions  - unit1,2Web technologies quiz questions  - unit1,2
Web technologies quiz questions - unit1,2
Sasidhar Kothuru
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
Sasidhar Kothuru
 
Xml sasidhar
Xml  sasidharXml  sasidhar
Xml sasidhar
Sasidhar Kothuru
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
Sasidhar Kothuru
 

More from Sasidhar Kothuru (20)

Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Spsl by sasidhar 3 unit
Spsl by sasidhar  3 unitSpsl by sasidhar  3 unit
Spsl by sasidhar 3 unit
 
Spsl unit1
Spsl   unit1Spsl   unit1
Spsl unit1
 
Spsl II unit
Spsl   II unitSpsl   II unit
Spsl II unit
 
Servlets
ServletsServlets
Servlets
 
Servers names
Servers namesServers names
Servers names
 
Servers names
Servers namesServers names
Servers names
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
Xml quiz 3 unit
Xml quiz   3 unitXml quiz   3 unit
Xml quiz 3 unit
 
Web technologies quiz questions - unit1,2
Web technologies quiz questions  - unit1,2Web technologies quiz questions  - unit1,2
Web technologies quiz questions - unit1,2
 
Web technologies 4th unit quiz
Web technologies 4th unit quizWeb technologies 4th unit quiz
Web technologies 4th unit quiz
 
Xml quiz 3 unit
Xml quiz   3 unitXml quiz   3 unit
Xml quiz 3 unit
 
Web technologies quiz questions - unit1,2
Web technologies quiz questions  - unit1,2Web technologies quiz questions  - unit1,2
Web technologies quiz questions - unit1,2
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Xml sasidhar
Xml  sasidharXml  sasidhar
Xml sasidhar
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 

Recently uploaded

Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 

Recently uploaded (20)

Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 

Jdbc sasidhar

  • 1. JDBC – Java DataBase Connectivity Sasidhar
  • 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  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. Advantages 1. Simplified Enterprise Development: By integrating with java JDBC code becomes very less. It is simple to install and maintain. Easy to write JDBC program 2. Zero Configuration for Network computers: No configuration is required. We require a suitable driver to connect to the database. It may be a bridge driver or a driver written in java. 3. Full Access to Metadata: JDBC API includes classes and interfaces to obtain metadata. 4. No Installation:
  • 4. 5. Database connection identified by URL: connectivity through DataSource object. Data source objects can provide connection pooling and transaction management. 6. Included in the J2EE platform: As JDBC API is needed in enterprise applications to connect to databases, it is included in the java2.0 Enterprise Edition. Advantages
  • 5. JDBC API  It contains two main interfaces. 1. An API for application writers and 2. A lower level driver API for driver writers. The set of classes that implement these lower level API interfaces for a particular database engine is called a JDBC driver A program needs a specific driver to connect to a specific database
  • 6. Popular Drivers Driver RDBMS Oracle.jdbc.driver.OracleDriver ORACLE Com.mysql.jdbc.Driver MySQL Com.sybase.jdbc.SybDriver Sybase Com.microsoft.jdbc.sqlserver.SQLServer Driver SQL Server Com.ibm.db2.jdbc.net.DB2Driver DB2 Org.hsqldbJdbcDriver HSQL DB
  • 7. Types of Drivers 1. Type1 ( JDBC-ODBC bridge + ODBC driver) 2. Type2 (partial JDBC driver) 3. Type3 (pure java JDBC driver for database middleware) 4. Type4 (pure Java JDBC driver with a direct database connection)
  • 8. Type 1 driver  Allows an application to access database through an intermediate ODBC driver.  It provides a gateway to the ODBC API Disadvantages: 1. ODBC binary code must be loaded on each client machine that uses this driver, limiting the usefulness of this type of driver for the internet 2. Translation overhead between JDBC and ODBC 3. User is limited by the functionality of the underlying ODBC driver. 4. Doesn’t support all the features of java. 5. It only works under the Microsoft windows and Sun Solaris operating systems.
  • 9. Type 2, 3,4 Drivers  Type 2-driver converts JDBC calls into client API calls for the DBMS. Also communicates directly with the database server. This driver offers better performance than type 1 driver.  Type-3 driver is completely implemented in java, hence it is a pure java JDBC driver. It translates JDBC calls into the middleware vendors’ protocol and translated to a DBMS protocol by a middleware server.  Type-4 drivers talks directly to the database using java sockets. These type of drivers are completely implemented in java to achieve platform independence and eliminate deployment issues. This type of drivers comes from the database vendor.
  • 10. 10 General Architecture  What design pattern is implied in this architecture?  What does it buy for us?  Why is this architecture also multi-tiered?
  • 11. 11
  • 12. 12 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
  • 13. 13 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:@oracl e-prod:1521:OPROD", username, passwd);  What do you think this statement does?  Establishes connection to database by obtaining a Connection object
  • 14. 14 2. Create JDBC statement(s)  Statement stmt = con.createStatement() ;  Creates a Statement object for sending SQL statements to the database
  • 15. 15 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);
  • 16. 16 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"); }
  • 18. 18 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.
  • 19. 19 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
  • 20. 20 Another way to access database (JDBC-ODBC) What’s a bit different about this architecture? Why add yet another layer?
  • 21. 21 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");
  • 22. 22 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); } } }
  • 24. 24 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 …
  • 25. 25 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(); }
  • 26. 26 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.
  • 27. 27 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 ); …
  • 28. 28 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) ); } }
  • 29. 29 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
  • 30. JDBC API PreparedStatement • Represents a precompiled SQL statement • Can be used to efficiently execute statement multiple times • Somewhat flexible – can create new ones as needed A prepared statement can contain variables that you supply each time you execute the statement.
  • 31. Optimized Statements  Prepared Statements  SQL calls that you make again and again  allows driver to optimize (compile) queries  created with Connection.prepareStatement()  Stored Procedures  written in DB-specific language  stored inside database  accessed with Connection.prepareCall()
  • 32. Prepared Statements Performance  Prepared Statements are more efficient than Statements when executing SQL statements multiple times and with different parameter values.
  • 33. Prepared Statements  PreparedStatements execute more efficiently than Statement objects  PreparedStatements can specify parameters
  • 34. PreparedStatements  PreparedStatement to locate all book titles for an author with a specific last name and first name, and to execute that query for several authors:  PreparedStatement authorBooks = connection.prepareStatement( "SELECT lastName, firstName, title " + "FROM authors INNER JOIN authorISBN " + "ON authors.authorID=authorISBN.authorID " + "INNER JOIN titles " + "ON authorISBN.isbn=titles.isbn " + "WHERE lastName = ? AND firstName = ?" );  Question marks (?) are placeholders for values that will be passed as part of the query to the database
  • 35. PreparedStatements  Program must specify the parameter values by using the PreparedStatement interface’s set methods.  For the preceding query, both parameters are strings that can be set with PreparedStatement method setString as follows: authorBooks.setString( 1, "Deitel" ); authorBooks.setString( 2, "Paul" );  setString automatically escapes String parameter values as necessary (e.g., the quote in the name O’Brien)
  • 36. Prepared Statement Example PreparedStatement updateSales; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME like ?"; updateSales = con.prepareStatement(updateString); int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = {"Colombian", "French_Roast", "Espresso","Colombian_Decaf","French_Roast_Decaf"}; int len = coffees.length; for(int i = 0; i < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); }
  • 38. The Callable Statement Object  A Callable Statement object holds parameters for calling stored procedures.  A callable statement can contain variables that you supply each time you execute the call.  When the stored procedure returns, computed values (if any) are retrieved through the Callable Statement object.
  • 39. JDBC API java.sql.CallableStatement • Used to execute SQL stored procedures. • Same syntax as PreparedStatement. • Least flexible. • Most optimized DB call.
  • 40. CallableStatement cstmt = conn.prepareCall("{call " + ADDITEM + "(?,?,?)}"); cstmt.registerOutParameter(2,Types.INTEGER); cStmt.registerOutParameter(3,Types.DOUBLE); How to Create a Callable Statement  Register the driver and create the database connection.  Create the callable statement, identifying variables with a question mark (?).
  • 41. How to Execute a callable Statement How to Execute a callable Statement cstmt.setXXX(index, value); cstmt.execute(statement); var = cstmt.getXXX(index);
  • 43. Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages (JSPs) Located @ DBLab Located @ Your PC Located @ Any PC
  • 44. import java.sql.*;   class JdbcTest { public static void main (String args []) throws SQLException { // Load Oracle driver DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // Connect to the local database Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@myhost:1521:ORCL","scott", "tiger"); JDBC
  • 45. // Query the student names Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("SELECT name FROM Student"); // Print the name out //name is the 2nd attribute of Student while (rset.next ()) System.out.println (rset.getString (2));  //close the result set, statement, and the connection rset.close(); stmt.close(); conn.close();
  • 46. JSP Syntax  Comment  <%-- Comment --%>  Expression  <%= java expression %>  Scriplet  <% java code fragment %>  Include  <jsp:include page="relativeURL" />
  • 47. Entry Form - First Attempt <b>Data Entry Menu</b> <ul> <li> <a href="courses.jsp">Courses<a> </li> <li> <a href="classes.jsp">Classes<a> </li> <li> <a href="students.jsp">Students<a> </li> </ul> Menu HTML Code
  • 48. Entry Form - First Attempt <html> <body> <table> <tr> <td> <jsp:include page="menu.html" /> </td> <td> Open connection code Statement code Presentation code Close connection code </td> </tr> </table> </body> </html> JSP Code
  • 49. Entry Form - First Attempt <%-- Set the scripting language to java and --%> <%-- import the java.sql package --%> <%@ page language="java" import="java.sql.*" %> <% try { // Load Oracle Driver class file DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // Make a connection to the Oracle datasource Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@feast.ucsd.edu:1521:source", “user", “pass"); %> Open Connectivity Code
  • 50. Entry Form - First Attempt <% // Create the statement Statement statement = conn.createStatement(); // Use the statement to SELECT the student attributes // FROM the Student table. ResultSet rs = statement.executeQuery ("SELECT * FROM Student"); %> Statement Code
  • 51. Entry Form - First Attempt <table> <tr> <th>SSN</th> <th>First</th> <th>Last</th> <th>College</th> </tr> <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> </table> Presentation Code
  • 52. Entry Form - First Attempt
  • 53. Entry Form - First Attempt <tr> <%-- Get the SSN, which is a number --%> <td><%= rs.getInt("SSN") %></td> <%-- Get the ID --%> <td><%= rs.getString("ID") %></td> <%-- Get the FIRSTNAME --%> <td><%= rs.getString("FIRSTNAME") %></td> <%-- Get the LASTNAME --%> <td><%= rs.getString("LASTNAME") %></td> <%-- Get the COLLEGE --%> <td><%= rs.getString("COLLEGE") %></td> </tr> Iteration Code
  • 54. Entry Form - First Attempt <% // Close the ResultSet rs.close(); // Close the Statement statement.close(); // Close the Connection conn.close(); } catch (SQLException sqle) { out.println(sqle.getMessage()); } catch (Exception e) { out.println(e.getMessage()); } %> Close Connectivity Code
  • 55. Entry Form - Second Attempt
  • 56. Entry Form - Second Attempt <html> <body> <table> <tr> <td> Open connection code Insertion Code Statement code Presentation code Close connection code </td> </tr> </table> </body> </html> JSP Code
  • 57. Entry Form - Second Attempt // Check if an insertion is requested String action = request.getParameter("action"); if (action != null && action.equals("insert")) { conn.setAutoCommit(false); // Create the prepared statement and use it to // INSERT the student attrs INTO the Student table. PreparedStatement pstmt = conn.prepareStatement( ("INSERT INTO Student VALUES (?, ?, ?, ?, ?)")); pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN"))); pstmt.setString(2, request.getParameter("ID")); … pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); } Insertion Code
  • 58. Entry Form - Second Attempt <table> <tr> <th>SSN</th> <th>First</th> <th>Last</th> <th>College</th> </tr> Insert Form Code <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> </table> Presentation Code
  • 59. Entry Form - Second Attempt <tr> <form action="students.jsp" method="get"> <input type="hidden" value="insert" name="action"> <th><input value="" name="SSN" size="10"></th> <th><input value="" name="ID" size="10"></th> <th><input value="" name="FIRSTNAME" size="15"></th> <th><input value="" name="LASTNAME" size="15"></th> <th><input value="" name="COLLEGE" size="15"></th> <th><input type="submit" value="Insert"></th> </form> </tr> Insert Form Code
  • 60. Entry Form - Third Attempt
  • 61. Entry Form - Third Attempt <html> <body> <table> <tr> <td> Open connection code Insertion Code Update Code Delete Code Statement code Presentation code Close connection code </td> </tr> </table> </body> </html> JSP Code
  • 62. Entry Form - Third Attempt // Check if an update is requested if (action != null && action.equals("update")) { conn.setAutoCommit(false); // Create the prepared statement and use it to // UPDATE the student attributes in the Student table. PreparedStatement pstatement = conn.prepareStatement( "UPDATE Student SET ID = ?, FIRSTNAME = ?, " + "LASTNAME = ?, COLLEGE = ? WHERE SSN = ?"); pstatement.setString(1, request.getParameter("ID")); pstatement.setString(2, request.getParameter("FIRSTNAME")); … int rowCount = pstatement.executeUpdate(); conn.setAutoCommit(false); conn.setAutoCommit(true); } Update Code
  • 63. Entry Form - Third Attempt // Check if a delete is requested if (action != null && action.equals("delete")) { conn.setAutoCommit(false); // Create the prepared statement and use it to // DELETE the student FROM the Student table. PreparedStatement pstmt = conn.prepareStatement( "DELETE FROM Student WHERE SSN = ?"); pstmt.setInt(1, Integer.parseInt(request.getParameter("SSN"))); int rowCount = pstmt.executeUpdate(); conn.setAutoCommit(false); conn.setAutoCommit(true); } Delete Code
  • 64. Entry Form - Third Attempt <table> <tr> <th>SSN</th> <th>First</th> <th>Last</th> <th>College</th> </tr> Insert Form Code <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> </table> Presentation Code
  • 65. Entry Form - Third Attempt <tr> <form action="students.jsp" method="get"> <input type="hidden" value="update" name="action"> <td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td> <td><input value="<%= rs.getString("ID") %>" name="ID"></td> … <td><input type="submit" value="Update"></td> </form> <form action="students2.jsp" method="get"> <input type="hidden" value="delete" name="action"> <input type="hidden" value="<%= rs.getInt("SSN") %>" name="SSN"> <td><input type="submit" value="Delete"></td> </form> </tr> Iteration Code

Editor's Notes

  1. The CallableStatement Object The way to access stored procedures using JDBC is through the CallableStatement class which is inherited from the PreparedStatement class. CallableStatement is like PreparedStatement in that you can specify parameters using the question mark (?) notation, but it contains no SQL statements. Both functions and procedures take parameters represented by identifiers. A function executes some procedural logic and it returns a value that can be any data type supported by the database. The parameters supplied to the function do not change after the function is executed. A procedure executes some procedural logic but does not return any value. However, some of the parameters supplied to the procedure may have their values changed after the procedure is executed. Note: Calling a stored procedure is the same whether the stored procedure was written originally in Java or in any other language supported by the database, such as PL/SQL. Indeed, a stored procedure written in Java appears to the programmer as a PL/SQL stored procedure.
  2. Creating a Callable Statement First you need an active connection to the database in order to obtain a CallableStatement object. Next, you create a CallableStatement object using the prepareCall() method of the Connection class. This method typically takes a string as an argument. The syntax for the string has two forms. The first form includes a result parameter and the second form does not: {? = call proc (…) } // A result is returned into a variable{call proc (…) } // Does not return a result In the example in the slide, the second form is used, where the stored procedure in question is ADDITEM. Note that the parameters to the stored procedures are specified using the question mark notation used earlier in PreparedStatement. You must register the data type of the parameters using the registerOutParameter() method of CallableStatement if you expect a return value, or if the procedure is going to modify a variable (also known as an OUT variable). In the example in the slide, the second and third parameters are going to be computed by the stored procedure, whereas the first parameter is an input (the input is specified in the next slide). Parameters are referred to sequentially, by number. The first parameter is 1. To specify the data type of each OUT variable, you use parameter types from the Types class. When the stored procedure successfully returns, the values can be retrieved from the CallableStatement object.
  3. How to Execute a Callable Statement There are three steps in executing the stored procedure after you have registered the types of the OUT variables: 1.Set the IN parameters. Use the setXXX() methods to supply values for the IN parameters. There is one setXXX() method for each Java type: setString(), setInt(), and so on. You must use the setXXX() method that is compatible with the SQL type of the variable. You can use setObject() with any variable type. Each variable has an index. The index of the first variable in the prepared statement is 1, the index of the second is 2, and so on. If there is only one variable, its index is 1. 2.Execute the call to the stored procedure. Execute the procedure using the execute() method. 3.Get the OUT parameters. Once the procedure is completed, you retrieve OUT variables, if any, using the getXXX() methods. Note that these methods must match the types you registered in the previous slide. Instructor Note The stored procedures lesson contains an example of executing a callable statement.