Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH

Similar presentations


Presentation on theme: "Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH"— Presentation transcript:

1 Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH
import java.sql.*; Class.forName("oracle.jdbc.driver.OracleDriver"); System.setProperty("oracle.net.tns_admin", "G://Applications//Oracle//ADMIN"); Connection conn = 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 Create statement Specify the connection Execute query Obtain results Clean 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 Tools and Bindings with languages

2 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

3 jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1
Connection Details Driver Type Username/password (optional) Connect string Connect string variants (no support for clustering, needs changing) (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) (since , requires oracle.net.tns_admin property) TNSNAMES.ORA entry example 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)))) Oracle Tools and Bindings with languages

4 Basic JDBC Use import java.sql.*; Class.forName("oracle.jdbc.driver.OracleDriver"); System.setProperty("oracle.net.tns_admin", "G://Applications//Oracle//ADMIN"); Connection conn = 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 Create statement Specify the connection Execute query Obtain results Clean up The property can also be specified (or overridden) via the command line: java -Doracle.net.tns_admin=G:\Applications\Oracle\Admin … Oracle Tools and Bindings with languages

5 Use of Prepared Statements
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 injection Use whenever possible Oracle Tools and Bindings with languages

6 Calling PL/SQL from Java
// Function CallableStatement stmt = conn.prepareCall("{?= call supervisor.team_leader(?, ?, ?)}"); // Procedure CallableStatement stmt2 = conn.prepareCall("{call supervisor.team_leader(?, ?, ?)}"); stmt.registerOutParameter(1, Types.NUMERIC); stmt.registerOutParameter(4, Types.VARCHAR); stmt.setInt(2, ); 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)); package supervisor function team_leader(institute in varchar, date in date, result out varchar) All OUT and INOUT parameters have to be registered Indices start from 1 In case of a function, the first parameter is the result Oracle Tools and Bindings with languages

7 conn.setAutoCommit(false/true);
Commits and rollbacks conn.setAutoCommit(false/true); true - statements are committed individually false - 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 Oracle Tools and Bindings with languages

8 Proper Exception Handling
JDK 1.7 JDK < 1.7 try ( Connection conn = …; PreparedStatement stmt = … ; ResultSet rset = … ; ) { // Some database operations } catch (Exception e) { // Handle the exception (e.g. logging) 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(): IF NOT: Run out of connections Run out of database sessions May crash both yours and other apps running on the database Oracle Tools and Bindings with languages

9 JSP Example (using JSTL)
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%'" <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 Pages JSTL = JSP Standard Tag Library CERN Java Web Hosting: Oracle Tools and Bindings with languages

10 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

11 Further Information E-mail: Rostislav.Titov@cern.ch
Oracle Database JDBC Developer's Guide and Reference: Oracle Tools and Bindings with languages


Download ppt "Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH"

Similar presentations


Ads by Google