0% found this document useful (0 votes)
40 views16 pages

Embedded SQL: Embedded SQL Is A Method of Combining The Computing Power of

Embedded SQL allows programmers to embed SQL statements in programs written in various languages like C/C++, COBOL and Fortran. The embedded SQL statements are preprocessed and replaced with calls to a library. This allows static checking of SQL statements at translation time, making programs more robust compared to JDBC. SQLJ provides a simpler syntax than JDBC for embedding SQL in Java programs.

Uploaded by

9897856218
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views16 pages

Embedded SQL: Embedded SQL Is A Method of Combining The Computing Power of

Embedded SQL allows programmers to embed SQL statements in programs written in various languages like C/C++, COBOL and Fortran. The embedded SQL statements are preprocessed and replaced with calls to a library. This allows static checking of SQL statements at translation time, making programs more robust compared to JDBC. SQLJ provides a simpler syntax than JDBC for embedding SQL in Java programs.

Uploaded by

9897856218
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

Embedded SQL

Embedded SQL is a method of combining the computing power of a programming language and the database manipulation capabilities of SQL. Embedded SQL statements are SQL statements written inline with the program source code of the host language. The embedded SQL statements are parsed by an embedded SQL preprocessor and replaced by host-language calls to a code library. The output from the preprocessor is then compiled by the host compiler. This allows programmers to embed SQL statements in programs written in any number of languages such as: C/C++, COBOL and Fortran. The ANSI SQL standards committee defined the embedded SQL standard in two steps: a formalism called Module Language was defined, then the embedded SQL standard was derived from Module Language.The SQL standard defines embedding of SQL as embedded SQL and the language in which SQL queries are embedded is referred to as the host language
Specific Features of the SQLJ Version of the Code Note the following features of the SQLJ version of the sample code: An explicit connection is not required. SQLJ can use a default connection context that has been initialized previously in the application.

No data type casting is required.

SQLJ does not require knowledge of _SQL_TYPECODE, _SQL_NAME, or factories.

NULL value data is processed implicitly.

No explicit code for resource management (for example, closing statements or results sets) is required.

SQLJ embeds host variables, in contrast to JDBC, which uses parameter markers.

String concatenation for long SQL statements is not required.


You do not have to register output parameters.

SQLJ syntax is simpler. For example, SELECT INTO statements are supported and ODBC-style escapes are not used.

You do not have to implement your own statement cache. By default, SQLJ will automatically cache #sql statements. This results in improved performance, for example, if you repeatedly call getEmployeeAddress() and updateAddress().

SQLJ Runtime
This section presents information about the Oracle SQLJ runtime, which is a thin layer of pure Java code that runs above the JDBC driver. When Oracle SQLJ translates your SQLJ source code, embedded SQL commands in your Java application are replaced by calls to the SQLJ runtime. Runtime classes act as wrappers for equivalent JDBC classes, providing special SQLJ functionality. When the end user runs the application, the SQLJ runtime acts as an intermediary, reading information about your SQL operations from your profile and passing instructions along to the JDBC driver. A SQLJ runtime can be implemented to use any JDBC driver or vendor-proprietary means of accessing the database. The Oracle SQLJ runtime requires a JDBC driver but can use any standard JDBC driver. To use Oracle-specific database types and features, however, you must use an Oracle JDBC driver. For the purposes of this document, it is generally assumed that you

are using an Oracle database and one of the Oracle JDBC drivers.

Packages Used Directly


This section lists packages containing classes you can import and use directly in your application. Packages whose names begin with oracle are for Oracle-specific SQLJ features.

sqlj.runtime
This package includes the ExecutionContext class, ConnectionContext interface, ResultSetIterator interface, and wrapper classes for streams (binary, ASCII, and Unicode). Interfaces and abstract classes in this package are implemented by classes in the sqlj.runtime.ref package or by classes generated by the SQLJ translator.

sqlj.runtime.ref
The classes in this package implement interfaces and abstract classes in the sqlj.runtime package. You will likely use the sqlj.runtime.ref.DefaultContext class, which is used to specify your default connection and create default connection context instances. The other classes in this package are used internally by SQLJ in defining classes during code generation, such as iterator classes and connection context classes that you declare in your SQLJ code.

oracle.sqlj.runtime
This package contains the Oracle class that you can use to instantiate the DefaultContext class and establish your default connection. It also contains Oraclespecific runtime classes used by the Oracle implementation of SQLJ, including functionality to convert to and from Oracle type extensions.

Packages Used Indirectly


This section lists packages containing classes that are for internal use by SQLJ.

sqlj.runtime.profile
This package contains interfaces and abstract classes that define what SQLJ profiles look like. This includes the EntryInfo class and TypeInfo class. Each entry in a profile is described by an EntryInfo object (where a profile entry corresponds to a SQL operation in your application). Each parameter in a profile entry is described by a TypeInfo object. The interfaces and classes in this package are implemented by classes in the sqlj.runtime.profile.ref package.

sqlj.runtime.profile.ref
This package contains classes that implement the interfaces and abstract classes of the sqlj.runtime.profile package, and are used internally by the SQLJ translator in defining profiles. It also provides the default JDBC-based runtime implementation.

sqlj.runtime.error
This package, used internally by SQLJ, contains resource files for all generic (nonOracle-specific) error messages that can be generated by the SQLJ translator.

oracle.sqlj.runtime.error
This package, used internally by SQLJ, contains resource files for all Oracle-specific error messages that can be generated by the SQLJ translator.

Categories of Runtime Errors


Runtime errors can be generated by any of the following:

SQLJ runtime JDBC driver RDBMS

In any of these cases, a SQL exception is generated as an instance of the java.sql.SQLException class or a subclass (such as sqlj.runtime.SQLNullException).

DefaultContext
public class DefaultContext extends ConnectionContextImpl implements ConnectionContext

The default context class provides a complete default implementation of a connection context. This is the same class definition that would have been generated by the reference translator for the clause: #sql public context DefaultContext; The reference implementation defaults to this class when no connection context instance variable exists in an executable sql clause and no other default class name was provided to the translator.

(2) ConnectionContextImpl

public abstract class ConnectionContextImpl extends java.lang.Object implements ConnectionContext

The connection context impl class is an abstract implementation of the connection context interface. It does not implement the connection context interface directly, but rather just defines the connection context method implementations. Subclasses must be defined which provide the static methods and constructors described in the connection context documentation. Generated context classes will extend this class and implement the connection context interface.

(3) ConnectionContext
public abstract interface ConnectionContext
A connection context manages a set of SQL operations performed during a session with a specific database. A connection context maintains an JDBC Connection instance on which dynamic SQL operations may be performed. It also contains a default execution context object by which sql operation execution semantics may be queried and modified.

getDefaultContext
public static DefaultContext getDefaultContext()

Returns the default context instance associated with this context class. If a default context has been explicitely installed via a call to setDefaultContext, that context is returned. Otherwise, if a default JDBC connection exists in the current runtime context, a new default context object is created, installed and returned which uses the default JDBC connection as its underlying connection. If no default connection exists in the runtime, null is returned.

What Is SQLJ?
SQLJ is an emerging database programming tool that allows embedding of static SQL statements in Java programs, very much like Pro*C or Pro*C++. SQLJ is an attractive alternative to JDBC because it allows translation-time syntax and semantics checking of static SQL statements. As a consequence, application programs developed in SQLJ are more robust. SQLJs syntax is also much more compact than that of JDBC, resulting in shorter programs and increased user productivity. The SQLJ translator converts Java programs embedded with static SQL statements into pure Java code, which can then be executed through a JDBC driver against the database. Programmers can also perform dynamic SQL access to the database using JDBC features.

Simple Example
A simple program in SQLJ is presented in this section. This program illustrates the

essential steps that are needed to write an SQLJ program. These steps follow: 1. Import necessary classes. In addition to the JDBC classes, java.sql.*, every SQLJ program will need to include the SQLJ run-time classes sqlj.runtime.* and sqlj.runtime.ref.*. In addition, to establish the default connection to Oracle, the Oracle class from the oracle.sqlj.runtime.* package is required. So, a typical set of statements to import packages would be:
import import import import import java.sql.*; sqlj.runtime.*; sqlj.runtime.ref.*; java.io.*; oracle.sqlj.runtime.*;

2. Register the JDBC driver, if needed. If a non-Oracle JDBC driver is being used, a call to the registerDriver method of the DriverManager class is necessary. For the purposes of this chapter, an Oracle JDBC driver is assumed. Therefore, this statement is not shown in any of the examples.

3. Connect to the database.

Connecting to the Oracle database is done by first obtaining a DefaultContext object using the getConnection method (of the Oracle class1), whose specification is
public static DefaultContext getConnection(String url,String user,String password,boolean autoCommit)throws SQLException

url is the database URL, and user and password are the Oracle user ID and password, respectively. Setting autoCommit to true would create the connection in autocommit mode, and setting it to false would create a connection in which the transactions must be committed by the programmer. A sample invocation is shown here:
DefaultContext cx1 =Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger",true);

1. The Oracle class can be found in the package oracle.sqlj.runtime.*.

The DefaultContext object so obtained is then used to set the static default context, as follows:

DefaultContext.setDefaultContext(cx1);
This DefaultContext object now provides the default connection to the database. 4. Embed SQL statements in the Java program. Once the default connection has been established, SQL statements can be embedded within the Java program using the following syntax:

#sql {<sql-statement>}
where #sql indicates to the SQLJ translator, called sqlj, that what follows is an SQL statement and <sql-statement> is any valid SQL statement, which may include host variables and host expressions. Host variables are prefixed with a colon, much like in Pro*C/Pro*C++.

The following simple SQLJ program performs a query


import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; public class Simple1 { public static void main (String args[]) throws SQLException {
DefaultContext cx1 =Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger");

DefaultContext.setDefaultContext(cx1); String cn; int mcode=101; try { #sql {select name into :cn from emptable where code = :mcode}; } catch (SQLException e) { System.out.println("Invalid symbol."); return; } System.out.println("\n Company Name = " + cn); } }
The program uses several Java variables (host variables) in the SQL

query. It also checks to see if any of the values returned from the database are nulls. A null value returned by the query is indicated by a Java null reference for the host variable into which the database value is retrieved. This feature of SQLJ implies that whenever there is a possibility of a null value being retrieved into a host variable, the host variables Java type should not be a primitive type.

Compiling SQLJ Programs


The SQLJ translator takes as input an SQLJ program file (with suffix .sqlj) and produces a .java file along with several other SQLJ profile files that contain the classes necessary to perform the SQL operations. The translator also automatically invokes the Java compiler to produce a .class file.There are several commandline parameters that can be given to the SQLJ translator.For example, if the users want online semantics checking of SQL statements, they can specify the following command-line options in compiling the Simple1.sqlj program:

Program For Creating Table Through SQLJ Program


import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; import java.util.*; public class Simple2 { public static void main (String args[]) throws SQLException { DefaultContext cx1=Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger"); DefaultContext.setDefaultContext(cx1); try { #sql {create table emptable2(code number(5),name varchar2(70),desig varchar2(30),salary number(7))};

} catch (SQLException e) { System.out.println("Invalid symbol."); return; } } }

Program for Inserting Record and using iterator for MultiRow Query
import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; import java.util.*; #sql iterator Empter(int code,String name,String desig,int salary); public class Simple4 { public static void main (String args[]) throws SQLException { DefaultContext cx1=Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger"); DefaultContext.setDefaultContext(cx1); Scanner sr=new Scanner(System.in); int mcode,msal; String mname,mdesig; System.out.println("Enter Code "); mcode=sr.nextInt(); System.out.println("Enter Name "); mname=sr.next(); System.out.println("Enter Designation "); mdesig=sr.next(); System.out.println("Enter Salary "); msal=sr.nextInt(); try { #sql {Insert Into emptable2 values(:mcode,:mname,:mdesig,:msal)}; #sql {COMMIT}; } catch (SQLException e) { System.out.println("Invalid symbol."); return; } Empter enrow=null; try { #sql enrow={Select code,name,desig,salary from emptable2};

while(enrow.next()) {
System.out.println(enrow.code()+" "+enrow.name()+" "+enrow.desig()+" "+enrow.salary());

} } catch (SQLException e) { System.out.println(e); return; } } }

Program for Updating Record and using iterator for MultiRow Query
import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; import java.util.*; #sql iterator Empter(int code,String name,String desig,int salary); public class Simple5 { public static void main (String args[]) throws SQLException { DefaultContext cx1=Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger"); DefaultContext.setDefaultContext(cx1); Scanner sr=new Scanner(System.in); int mcode,msal; System.out.println("Enter Code Updating Record"); mcode=sr.nextInt(); try { #sql{update emptable2 set salary=7800 where code=:mcode}; #sql{commit}; } catch (SQLException e) { System.out.println("Error"); return; }

Empter enrow=null; try { #sql enrow={Select code,name,desig,salary from emptable2}; while(enrow.next()) {


System.out.println(enrow.code()+" "+enrow.name()+" "+enrow.desig()+" "+enrow.salary());

} } catch (SQLException e) { System.out.println(e); return; } } }

Program for Deleting Record and using iterator for MultiRow Query
import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; import java.util.*; #sql iterator Empter(int code,String name,String desig,int salary); public class Simple6 { public static void main (String args[]) throws SQLException { DefaultContext cx1=Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger"); DefaultContext.setDefaultContext(cx1); Scanner sr=new Scanner(System.in); int mcode,msal; System.out.println("Enter Code for Deleting Record"); mcode=sr.nextInt(); try { #sql{delete from emptable2 where code=:mcode}; #sql{commit};

} catch (SQLException e) { System.out.println("Error"); return; } Empter enrow=null; try { #sql enrow={Select code,name,desig,salary from emptable2}; while(enrow.next()) { System.out.println(enrow.code()+" "+enrow.salary()); } } catch (SQLException e) { System.out.println(e); return; } } }

"+enrow.name()+"

"+enrow.desig()+"

Use Of Commit and Rollback


import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; import java.util.*; public class Simple7 { public static void main (String args[]) throws SQLException { Scanner sr=new Scanner(System.in); DefaultContext cx1=Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger"); DefaultContext.setDefaultContext(cx1); int mcode,msal; String mname,mdesig;

System.out.println("Enter Code "); mcode=sr.nextInt(); System.out.println("Enter Name "); mname=sr.next(); System.out.println("Enter Designation "); mdesig=sr.next(); System.out.println("Enter Salary "); msal=sr.nextInt(); int cnt; try { #sql {SELECT count(*) INTO :cnt FROM emptable2 WHERE code=:mcode}; if(cnt==0) { #sql {Insert Into emptable2 values(:mcode,:mname,:mdesig,:msal)}; #sql {COMMIT}; } else { System.out.println("Code Already Exist"); #sql {ROLLBACK}; Oracle.close(); } } catch (SQLException e) { System.out.println("error"); return; } } }

Use Of Commit and Rollback And Data manipulation Function Like max,min
import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; import java.util.*; public class Simple8 { public static void main (String args[]) throws SQLException {

Scanner sr=new Scanner(System.in); DefaultContext cx1=Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger"); DefaultContext.setDefaultContext(cx1); int mcode,msal; String mname,mdesig; System.out.println("Enter Code "); mcode=sr.nextInt(); System.out.println("Enter Name "); mname=sr.next(); System.out.println("Enter Designation "); mdesig=sr.next(); System.out.println("Enter Salary "); msal=sr.nextInt(); int cnt; try { #sql {SELECT max(salary) INTO :cnt FROM emptable2}; System.out.println("Maximum Salary="+cnt); } catch (SQLException e) { System.out.println("error"); return; } } }

Program for Creating Procedure


import sqlj.runtime.*; import sqlj.runtime.ref.*; import java.sql.*; import oracle.sqlj.runtime.*; import java.util.*; public class Simple9 { public static void main (String args[]) throws SQLException { DefaultContext cx1=Oracle.getConnection("jdbc:oracle:oci8:@","scott","tiger");

DefaultContext.setDefaultContext(cx1); Scanner sr=new Scanner(System.in); int mcode; String mname=""; System.out.println("Enter Code for Testing Procedure Record"); mcode=sr.nextInt(); try { #sql{Create or replace procedure getEmpName(mcode IN Number,mname OUT VARCHAR)As Begin select name into mname from emptable2 where code=mcode; End;}; #sql {call getEmpName(:IN mcode,:OUT mname)}; #sql {commit}; System.out.println("Name = "+ mname); } catch (SQLException e) { System.out.println("No Data Found"); return; } } }

Install Oracle 9i Install Java 5 or 6 Version Check ora92 Folder in your drive. According to Folder give drive name in CLASSPATH Set This ClassPath
d:\oracle\ora92\sqlj\lib\translator.zip;d:\oracle\ora92\sqlj\lib\runtime12.zip;d:\oracle\ora92\sqlj\li b\classes12.zip;d:\oracle\ora92\jdbc\lib\classes12.jar;C:\Program Files\Java\jdk1.5.0_06\bin

You might also like