Upload
charlene-gallagher
View
222
Download
0
Embed Size (px)
Citation preview
Basic JDBC Use
Oracle Tools and Bindings with languages
import java.sql.*;… Class.forName("oracle.jdbc.driver.OracleDriver"); System.setProperty("oracle.net.tns_admin", "G://Applications//Oracle//ADMIN"); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1"); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("Select LAST_NAME from PERSONS where ORG_UNIT like 'IT%'"); while (rset.next()) System.out.println(rset.getString("LAST_NAME"));
rset.close();stmt.close();conn.close();
Load the Oracle JDBC driver
Set which TNSNAMES file to use
Specify the connectionCreate statement
Execute query
Obtain resultsClean up
• Oracle JDBC Drivers must be in the CLASSPATH• Preinstalled in the CERN Web Services infrastructure (thin)• Obtaining drivers: Google for “Oracle JDBC Drivers”
Oracle JDBC Driver Types
• Thin driver (works through TCP/IP)– Pure Java– Platform independent– Does not require Oracle Client Installation– Can be used in applets
• OCI driver (works through SQL*Net)– Better performance– Support OCI connection pooling– Caching results in the client’s memory– Requires Oracle Client Installation– Should match the database version– Platform specific
• Server-side internal driver (Java stored procedures)
Oracle Tools and Bindings with languages
Connection Details
Oracle Tools and Bindings with languages
jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1
cerndb1=(DESCRIPTION=(ADDRESS= (PROTOCOL=TCP) (HOST=pdb2-v.cern.ch) (PORT=1574) )(ADDRESS= (PROTOCOL=TCP) (HOST=pdb1-v.cern.ch) (PORT=1574) )(FAILOVER=on)(LOAD_BALANCE=off)(CONNECT_DATA= (SERVER=DEDICATED) (SERVICE_NAME=PDB_CERNDB1.cern.ch) (FAILOVER_MODE= (TYPE=SELECT) (METHOD=BASIC))))
Driver Type Username/password (optional) Connect string
1. @pdb2-v.cern.ch:1574/PDB_CERNDB1.cern.ch (no support for clustering, needs changing)
2. @(DESCRIPTION= (ADDRESS= (PROTOCOL=TCP) (HOST=pdb2-v.cern.ch) (PORT=1574) )(ADDRESS= (PROTOCOL=TCP) (HOST=pdb1-v.cern.ch) (PORT=1574) )(FAILOVER=on)(LOAD_BALANCE=off)(CONNECT_DATA= (SERVER=DEDICATED) (SERVICE_NAME=PDB_CERNDB1.cern.ch)(FAILOVER_MODE= (TYPE=SELECT) (METHOD=BASIC))))(long, needs changing after DB migration)
3. @cerndb1 (since 10.2.0.1.0, requires oracle.net.tns_admin property)
Connect string variants
TNSNAMES.ORA entry example
Basic JDBC Use
Oracle Tools and Bindings with languages
import java.sql.*;… Class.forName("oracle.jdbc.driver.OracleDriver"); System.setProperty("oracle.net.tns_admin", "G://Applications//Oracle//ADMIN"); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1"); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("Select LAST_NAME from PERSONS where ORG_UNIT like 'IT%'"); while (rset.next()) System.out.println(rset.getString("LAST_NAME"));
rset.close();stmt.close();conn.close();
Load the Oracle JDBC driver
Set which TNSNAMES file to use
Specify the connectionCreate statement
Execute query
Obtain resultsClean up
The property can also be specified (or overridden) via the command line:java -Doracle.net.tns_admin=G:\Applications\Oracle\Admin …
Use of Prepared Statements
Oracle Tools and Bindings with languages
PreparedStatement stmt = conn.prepareStatement("Select LAST_NAME from PERSONS where ORG_UNIT = ? and FIRST_NAME = ?");
stmt.setString(1, "IT");stmt.setString(2, "EVA");
ResultsSet rset = stmt.executeQuery();
Better performance (no query re-parsing)Protect from SQL injectionUse whenever possible
Calling PL/SQL from Java
Oracle Tools and Bindings with languages
// FunctionCallableStatement stmt = conn.prepareCall("{?= call supervisor.team_leader(?, ?, ?)}");// ProcedureCallableStatement stmt2 = conn.prepareCall("{call supervisor.team_leader(?, ?, ?)}");
stmt.registerOutParameter(1, Types.NUMERIC);stmt.registerOutParameter(4, Types.VARCHAR); stmt.setInt(2, 123456);stmt.setDate(3, new java.sql.Date((new java.util.Date()).getTime())); stmt.execute(); System.out.println(stmt.getInt(1));System.out.println(stmt.getString(4));
All OUT and INOUT parameters have to be registered Indices start from 1 In case of a function, the first parameter is the result
package supervisor
function team_leader(institute in varchar,date in date, result out varchar)
Commits and rollbacks
Oracle Tools and Bindings with languages
conn.setAutoCommit(false/true);true - statements are committed individuallyfalse - statements are grouped until commit() or rollback()
conn.commit();Commit the current transaction and release DB locks
conn.rollback();Rollback (undo) the current transaction
conn.rollback(savepoint);Undo the changes made after the given save point
N.B. Auto-commit is switched ON by default
Proper Exception Handling
Oracle Tools and Bindings with languages
Connection conn = null;PreparedStatement stmt = null;ResultSet rset = null;
try{ // Some database operations}catch (Exception e){ // Handle the exception (e.g. logging)}finally{ if (rset != null) rset.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close():}
try ( Connection conn = …; PreparedStatement stmt = … ; ResultSet rset = … ;) { // Some database operations}catch (Exception e){ // Handle the exception (e.g. logging)}
JDK 1.7 JDK < 1.7
IF NOT:
Run out of connections Run out of database sessions May crash both yours and other
apps running on the database
JSP Example (using JSTL)
Oracle Tools and Bindings with languages
CERN Java Web Hosting: http://webservices.web.cern.ch/
<%@ page contentType="text/html;charset=windows-1252"%><%@ taglib prefix="c" uri="/WEB-INF/tlds/c.tld"%><%@ taglib prefix="sql" uri="/WEB-INF/tlds/sql.tld"%>
<html><body> <sql:query var="result" sql="Select FIRST_NAME, LAST_NAME from PERSONS where ORG_UNIT like 'IT%'" dataSource="jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1"/> <table> <tr><th>First name</th><th>Last Name</th></tr> <c:forEach items="${result.rows}" var="row"> <tr><td>${row.FIRST_NAME}</td><td>${row.LAST_NAME}</td> </c:forEach> </table></body></html>
JSP = Java Server PagesJSTL = JSP Standard Tag Library
Beyond simple JDBC
• javax.sql.* package – DataSource, connection pooling, distributed transactions
• Lightweight connection pools (e.g. c3p0)– Opening a connection is costly -> reuse!– Use pooling for extensive DB use
• JDBC Abstraction Frameworks (e.g. Spring JDBC)– Simplify use of JDBC
• Object Relational Mappers (e.g. Hibernate)– Map Java objects to database tables– Handle object relationships– Save/load complex objects with a single command
Oracle Tools and Bindings with languages
Further Information
Oracle Tools and Bindings with languages
E-mail: [email protected]
Oracle Database JDBC Developer's Guide and Reference:
http://docs.oracle.com/cd/B28359_01/java.111/b31224/toc.htm