SlideShare uma empresa Scribd logo
1 de 65
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

Mais conteúdo relacionado

Mais procurados (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
 

Semelhante a 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
 

Mais de 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
 

Último

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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

Notas do Editor

  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.