Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright  Oracle Corporation, 1998. All rights reserved. 7 Accessing a Database Using SQLJ.

Similar presentations


Presentation on theme: "Copyright  Oracle Corporation, 1998. All rights reserved. 7 Accessing a Database Using SQLJ."— Presentation transcript:

1 Copyright  Oracle Corporation, 1998. All rights reserved. 7 Accessing a Database Using SQLJ

2 Copyright  Oracle Corporation, 1998. All rights reserved. 7-2 Objectives After completing this lesson, you should be able to do the following: Describe the design goals of SQLJ Connect to a database using SQLJ Perform DML and DDL operations Use AppBuilder for Java to precompile SQLJ code After completing this lesson, you should be able to do the following: Describe the design goals of SQLJ Connect to a database using SQLJ Perform DML and DDL operations Use AppBuilder for Java to precompile SQLJ code

3 Copyright  Oracle Corporation, 1998. All rights reserved. 7-3 Overview Java file compiled SQL code first parse Development time Run time Java with JDBC SQLJ Java file compiled SQLJ file pre- compiled SQL code first parse SQL JDBC

4 Copyright  Oracle Corporation, 1998. All rights reserved. 7-4 SQLJ is passed through a precompiler: Checks SQL against the database Generates Java code with JDBC calls SQLJ is passed through a precompiler: Checks SQL against the database Generates Java code with JDBC calls Using SQLJ SQLJ code Java code with JDBC calls Java compiler SQLJ preprocessor Oracle Regular Java class

5 Copyright  Oracle Corporation, 1998. All rights reserved. 7-5 Design Goals of SQLJ Allows easy embedding of SQL statements in Java source code – More concise than JDBC Early checking of SQL statements eliminates many run time errors: – SQL syntax errors – Incorrect assumption of table structures – Java/SQL type mismatch Allows easy embedding of SQL statements in Java source code – More concise than JDBC Early checking of SQL statements eliminates many run time errors: – SQL syntax errors – Incorrect assumption of table structures – Java/SQL type mismatch SQL

6 Copyright  Oracle Corporation, 1998. All rights reserved. 7-6 What Does SQLJ Look Like? SQL code is embedded in Java code File typically has a.sqlj extension Equivalent code using JDBC: SQL code is embedded in Java code File typically has a.sqlj extension Equivalent code using JDBC: void myJavaMethod() { #sql { create table EMP(EMPNO number(5) }; } void myJavaMethod() { Statement st = conn.createStatement(); st.execute("create table EMP(EMPNO number(5))"); } myfile.sqlj another.java

7 Copyright  Oracle Corporation, 1998. All rights reserved. 7-7 Imports needed SQLJ statement begins with #sql SQL statement placed in braces - can throw SQLException Imports needed SQLJ statement begins with #sql SQL statement placed in braces - can throw SQLException SQLJ Syntax: A Closer Look import java.sql.*; import sqlj.runtime.*; import sqlj.runtime.ref.*; class X { void myJavaMethod() { try { #sql{update EMP set SAL = SAL + 100 where SAL < 1500}; } catch (SQLException e) {…} }

8 Copyright  Oracle Corporation, 1998. All rights reserved. 7-8 Loading the JDBC Driver SQLJ requires that the JDBC driver class is loaded This can be performed in the same way as for JDBC: SQLJ requires that the JDBC driver class is loaded This can be performed in the same way as for JDBC: try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("Could not load the driver"); }

9 Copyright  Oracle Corporation, 1998. All rights reserved. 7-9 Specifying a Connection Context All SQLJ statements execute in a “connection context” Defines the database schema, session, and transaction All SQLJ statements execute in a “connection context” Defines the database schema, session, and transaction try { Class.forName(…); DefaultContext.setDefaultContext( new DefaultContext( "jdbc:oracle:thin:@HOSTID:1521:ORCL", "theUser", "thePassword") ); } catch (Exception e) {…}

10 Copyright  Oracle Corporation, 1998. All rights reserved. 7-10 Once the JDBC driver has been loaded, and a connection context has been set, SQLJ statements can be executed Executing the SQL Statement try { Class.forName(…); DefaultContext.setDefaultContext(…); #sql { update EMP set SAL = SAL + 100 where SAL < 1500 }; } catch (Exception e) {…}

11 Copyright  Oracle Corporation, 1998. All rights reserved. 7-11 Passing Host Variables into a SQLJ Statement A host variable is a variable in your Java program Host variables can be used in a SQLJ statement as follows: A host variable is a variable in your Java program Host variables can be used in a SQLJ statement as follows: void deleteHighEarners(BigDecimal amt) { try { #sql {delete from EMP where SAL >= :amt}; } catch (SQLException e) {…} }

12 Copyright  Oracle Corporation, 1998. All rights reserved. 7-12 Guided Practice: SQLJ and JDBC This example uses JDBC to give a pay raise to selected employees. How would it look in SQLJ? This example uses JDBC to give a pay raise to selected employees. How would it look in SQLJ? BigDecimal amt, low; … Class.forName(…); Connection conn = DriverManager.getConnection(…); PreparedStatement stmt = conn.prepareStatement ("update EMP set SAL = SAL + ? where SAL < ?"); stmt.setBigDecimal(1, amt); stmt.setBigDecimal(2, low); stmt.execute();

13 Copyright  Oracle Corporation, 1998. All rights reserved. 7-13 Assigning Results to Host Variables Host variables can be assignment targets, for values retrieved by SQL operations void printJobTitle(BigDecimal empno) { String job; try { #sql { select JOB into :job from EMP where EMPNO = :empno }; System.out.println("Job title is " + job); } catch (SQLException e) {} }

14 Copyright  Oracle Corporation, 1998. All rights reserved. 7-14 Dealing with Query Result Sets SQLJ can be used to execute queries that return a result set To process the result set, define an “iterator” type – Specifies the data type of each column – Use the iterator to retrieve columns SQLJ can be used to execute queries that return a result set To process the result set, define an “iterator” type – Specifies the data type of each column – Use the iterator to retrieve columns … select ENAME, SAL from EMP …

15 Copyright  Oracle Corporation, 1998. All rights reserved. 7-15 Defining a Named Iterator An iterator type can be defined as shown here, to retrieve columns by name: SQLJ translates this into a Java class called MyIter, with these methods: An iterator type can be defined as shown here, to retrieve columns by name: SQLJ translates this into a Java class called MyIter, with these methods: #sql iterator MyIter(String ENAME, String JOB); String ENAME()… // Get ENAME column String JOB()… // Get JOB column boolean next()… // Go to next row

16 Copyright  Oracle Corporation, 1998. All rights reserved. 7-16 Using a Named Iterator The iterator can be used to extract columns by name, in a type-safe manner #sql iterator MyIter(String ENAME, String JOB); class MyClass { void aMethod() { MyIter iter; #sql iter = { select ENAME, JOB from EMP }; while(iter.next()) { String ename = iter.ENAME(); String job = iter.JOB(); } …

17 Copyright  Oracle Corporation, 1998. All rights reserved. 7-17 Defining By-Position Iterators By-position iterators define the type of each column, but not a name Columns must be fetched by position: By-position iterators define the type of each column, but not a name Columns must be fetched by position: #sql iterator MyIter(String, String); … MyIter iter; String name, job; #sql iter = { select ENAME, JOB from EMP }; while(true) { #sql {fetch :iter into :name, :job}; if (iter.endFetch()) break; System.out.println(name + " is a " + job); …

18 Copyright  Oracle Corporation, 1998. All rights reserved. 7-18 Calling Stored Procedures and Stored Functions A SQLJ statement can call a stored procedure as follows: Stored functions are called as follows: A SQLJ statement can call a stored procedure as follows: Stored functions are called as follows: String ename = …; #sql { call PayBonus(:ename, 100) }; String dname = …; BigDecimal topSal; #sql topSal = { values( GetTopSal(:dname) ) };

19 Copyright  Oracle Corporation, 1998. All rights reserved. 7-19 Specifying a Different Database Connection A different connection context can be specified for SQLJ statements: #sql context MyDBContext; class MyClass { void aMethod() { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); MyDBContext ctxt = new MyDBContext( "jdbc:odbc:MyOtherDb", "user", "password"); #sql (ctxt) { select * from TABLEX }; … ctxt.close();

20 Copyright  Oracle Corporation, 1998. All rights reserved. 7-20 Using SQLJ in AppBuilder.sqlj files can be added directly to an AppBuilder project

21 Copyright  Oracle Corporation, 1998. All rights reserved. 7-21 Enabling Compile-Time SQL Checking Select Project—> Project Properties from Menu bar Check this check box Select Project—> Project Properties from Menu bar Check this check box

22 Copyright  Oracle Corporation, 1998. All rights reserved. 7-22 Specifying Connection Properties

23 Copyright  Oracle Corporation, 1998. All rights reserved. 7-23 Summary SQLJ enables you to embed SQL statements directly in Java code SQLJ statements are compiled statically, whereas JDBC is dynamic SQLJ statements begin with #sql Iterators and contexts can be defined – #sql iterator – #sql context SQLJ enables you to embed SQL statements directly in Java code SQLJ statements are compiled statically, whereas JDBC is dynamic SQLJ statements begin with #sql Iterators and contexts can be defined – #sql iterator – #sql context

24 Copyright  Oracle Corporation, 1998. All rights reserved. 7-24 Practice 7-1 Overview Create and build SQLJ files using AppBuilder tools Connect to a database using SQLJ Create and execute a query using SQJL Iterate a result set Perform an update operation Perform an update operation with parameters Create and build SQLJ files using AppBuilder tools Connect to a database using SQLJ Create and execute a query using SQJL Iterate a result set Perform an update operation Perform an update operation with parameters

25 Copyright  Oracle Corporation, 1998. All rights reserved. 7-25 Full Notes Page for Practices

26 Copyright  Oracle Corporation, 1998. All rights reserved. 7-26 Full Notes Page for Practices


Download ppt "Copyright  Oracle Corporation, 1998. All rights reserved. 7 Accessing a Database Using SQLJ."

Similar presentations


Ads by Google