SlideShare a Scribd company logo
1 of 22
Click to add Title
Embedded SQL, Dynamic SQL
and SQLJ
e-Infochips Institute of Training Research and Academics Limited
Prepared By:-
Dharita Chokshi
Outlines
• What is SQL
• What is Embedded SQL
• Cursors
• Dynamic SQL
• SQLJ
• Summary
What is SQL?
• Structured Query Language (SQL) is a standardized language
used to manipulate database objects and the data they
contain.
• It comprised of several different statements that are used
manipulate data values.
• SQL being a nonprocedural is not a general-purpose
programming language.
UPDATE EMPLOYEE SET LASTNAME = 'Jones' WHERE
EMPID = '001'
What is Embedded SQL?
• As a result, database applications are usually developed by
combining capabilities of a high-level programming language
with SQL.
• The simplest approach is to embed SQL statements directly
into the source code file(s) that will be used to create an
application. This technique is referred to as embedded SQL
programming.
• sqlca.h – header file to be included.
Embedded SQL
• High-level programming language compilers cannot interpret,
SQL statements.
• Hence source code files containing embedded SQL
statements must be preprocessed before compiling.
• Thus each SQL statement coded in a high-level programming
language source code file must be prefixed with the keywords
EXEC SQL and terminated with either a semicolon or the
keywords END_EXEC.
Embedded SQL
• Likewise, the Database Manager cannot work directly with
high-level programming language variables.
• Instead, it must use special variables known as host
variables to move data between an application and a
database.
• Two types of Host variables:-
1. Input Host Variables – Transfer data to database
2. Output Host Variables – receives data from database
Embedded SQL
• Host variables are ordinary programming language variables.
• To be set apart, they must be defined within a special section
known as a declare section.
EXEC SQL BEGIN DECLARE SECTION
char EmployeeID[7];
double Salary;
EXEC SQL END DECLARE SECTION
• Each host variable must be assigned a unique name
even though declared in different declaration section.
Embedded SQL
main() {
EXEC SQL BEGIN DECLARE SECTION;
int OrderID, CustID;
char SalesPerson[10], Status[6];
EXEC SQL END DECLARE SECTION;
printf ("Enter order number: ");
scanf ("%d", &OrderID);
EXEC SQL SELECT CustID, SalesPerson, Status FROM
Orders WHERE OrderID = :OrderID INTO :CustID,
:SalesPerson, :Status;
printf ("Customer number: %d n", CustID);
printf ("Salesperson: %s n", SalesPerson);
printf ("Status: %s n", Status);
}
Embedded SQL
Connecting to Database using embedded sql
EXEC SQL CONNECT :userid IDENTIFIED BY :passwd;
EXEC SQL CREATE TABLE Test (a int);
EXEC SQL INSERT INTO Test VALUES (1);
EXEC SQL SELECT MAX (a) INTO :value from R;
printf (“Max value=%dn”,value);
Cursor
• Can declare a cursor on a query statement which generates a
relation.
• Can open a cursor, repeatedly fetch a tuple, move the cursor,
until all tuples have been retrieved.
• Control order: ORDER BY, in queries that are accessed through
a cursor
• Can also modify/delete tuple pointed to by cursor.
• Must close cursor at end.
Cursor
EXEC SQL DECLARE myCursor CURSOR FOR SELECT bid
from Reservations;
EXEC SQL OPEN myCursor;
EXEC SQL WHENEVER NOT FOUND DO break;
while (1) {
EXEC SQL FETCH myCursor INTO :num;
}
EXEC SQL CLOSE myCursor;
Dynamic SQL
• Dynamic SQL means composing and executing new (not
previously compiled) SQL statements at run-time.
• Although static SQL statements are relatively easy to
incorporate, Dynamic SQL statements are much more flexible
as they can be constructed at run time.
• Dynamic queries can be complex because the type and
number of retrieved attributes are unknown at compile time.
INSERT INTO EMPLOYEES VALUES (?, ?)
DELETE FROM DEPARTMENT WHERE DEPTID = ?
SQLJ
• SQLJ – Standard for embedding SQL in Java
• Similar to existing SQL extensions provided for C, FORTRAN,
and other programming languages.
• IBM, Oracle, and several other companies proposed SQLJ as
a standard and as a simpler and easier-to-use alternative to
JDBC.
• An SQLJ translator converts SQL statements into Java
• These are executed through the JDBC interface
• Certain classes have to be imported E.g., java.sql
SQLJ
• SQLJ precompiles SQL code in a Java program.
• Provides greater compile-time checking of SQL statements.
• Reduces the amount of code needed to execute SQL from
within Java.
SQLJ v/s JDBC
// SQLJ
int n;
#sql { INSERT INTO emp VALUES (:n)};
// JDBC
int n;
Statement stmt = conn.prepareStatement
(“INSERT INTO emp VALUES (?)”);
stmt.setInt(1,n);
stmt.execute ();
stmt.close();
class X {
void myJavaMethod() {
try {
#sql{update EMP set SAL = SAL + 100
where SAL < 1500};
}
SQLJ
import java.sql.*;
import sqlj.runtime.*;
import sqlj.runtime.ref.*;
Imports Needed
SQL statement placed in braces
can throw SQLException
catch (SQLException e) {…}
}
SQLJ
Loading the JDBC Driver
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 driver");
}
SQLJ
Specifying a Connection Context
• All SQLJ statements execute in a “connection context”
• Plays similar role as a Connection object does in JDBC.
• Establishes the database we are connecting to, the user
name, and the password.
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
DefaultContext.setDefaultContext(new DefaultContext(
"jdbc:oracle:thin:@HOSTID:1521:ORCL",
"theUser", "thePassword") );
}
SQLJ
Passing Host Variables into a SQLJ
Statement
• Prefix the java variable name with a colon (:)
#sql {delete from EMP where SAL >= :amt};
SQLJ
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 that
specifies the data type of each column
#sql iterator MyIter(String ENAME, String JOB);
class MyClass {
MyIter iter;
#sql iter = { select ENAME, JOB from EMP };
while(iter.next()) {
String ename = iter.ENAME();
String job = iter.JOB();
}
When to Which ?
How do applications connect to a database?
• App ↔ DBMS: Embedded SQL
• App ↔ Driver ↔ DBMS: JDBC/ODBC or SQLJ
What mechanisms exist to retrieve/modify data?
• Static Queries: Embedded SQL, SQLJ
• Dynamic Queries: JDBC/ODBC, Dynamic SQL
Thank you

More Related Content

What's hot

1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQLrehaniltifat
 
15. Transactions in DBMS
15. Transactions in DBMS15. Transactions in DBMS
15. Transactions in DBMSkoolkampus
 
Entity Relationship Diagrams
Entity Relationship DiagramsEntity Relationship Diagrams
Entity Relationship Diagramssadique_ghitm
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship DiagramShakila Mahjabin
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functionsAmrit Kaur
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Elizabeth alexander
 
Register allocation and assignment
Register allocation and assignmentRegister allocation and assignment
Register allocation and assignmentKarthi Keyan
 
Structure of dbms
Structure of dbmsStructure of dbms
Structure of dbmsMegha yadav
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbmsshekhar1991
 
17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMSkoolkampus
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentationNITISH KUMAR
 

What's hot (20)

DBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCLDBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCL
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
15. Transactions in DBMS
15. Transactions in DBMS15. Transactions in DBMS
15. Transactions in DBMS
 
Acid properties
Acid propertiesAcid properties
Acid properties
 
Entity Relationship Diagrams
Entity Relationship DiagramsEntity Relationship Diagrams
Entity Relationship Diagrams
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
serializability in dbms
serializability in dbmsserializability in dbms
serializability in dbms
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship Diagram
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Register allocation and assignment
Register allocation and assignmentRegister allocation and assignment
Register allocation and assignment
 
Structure of dbms
Structure of dbmsStructure of dbms
Structure of dbms
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbms
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbms
 
Databases: Normalisation
Databases: NormalisationDatabases: Normalisation
Databases: Normalisation
 
17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMS
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 

Similar to SQL, Embedded SQL, Dynamic SQL and SQLJ

Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming LanguagesS.Shayan Daneshvar
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07AnusAhmad
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Generating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerGenerating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerRob van den Berg
 
java database connectivity for java programming
java database connectivity for java programmingjava database connectivity for java programming
java database connectivity for java programmingrinky1234
 
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentRapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentEmbarcadero Technologies
 
SQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersSQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersJerod Johnson
 
LM7_ Embedded Sql and Dynamic SQL in dbms
LM7_ Embedded Sql and Dynamic SQL in dbmsLM7_ Embedded Sql and Dynamic SQL in dbms
LM7_ Embedded Sql and Dynamic SQL in dbmsBalaKrish12
 

Similar to SQL, Embedded SQL, Dynamic SQL and SQLJ (20)

embedded-static-&dynamic
embedded-static-&dynamicembedded-static-&dynamic
embedded-static-&dynamic
 
Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming Languages
 
Chapter09
Chapter09Chapter09
Chapter09
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
 
stored.ppt
stored.pptstored.ppt
stored.ppt
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Generating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerGenerating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data Modeler
 
Jdbc
JdbcJdbc
Jdbc
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
SQL overview and software
SQL overview and softwareSQL overview and software
SQL overview and software
 
java database connectivity for java programming
java database connectivity for java programmingjava database connectivity for java programming
java database connectivity for java programming
 
Jdbc
JdbcJdbc
Jdbc
 
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentRapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
 
SQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersSQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API Consumers
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
LM7_ Embedded Sql and Dynamic SQL in dbms
LM7_ Embedded Sql and Dynamic SQL in dbmsLM7_ Embedded Sql and Dynamic SQL in dbms
LM7_ Embedded Sql and Dynamic SQL in dbms
 

Recently uploaded

A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf203318pmpc
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 

Recently uploaded (20)

A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 

SQL, Embedded SQL, Dynamic SQL and SQLJ

  • 1. Click to add Title Embedded SQL, Dynamic SQL and SQLJ e-Infochips Institute of Training Research and Academics Limited Prepared By:- Dharita Chokshi
  • 2. Outlines • What is SQL • What is Embedded SQL • Cursors • Dynamic SQL • SQLJ • Summary
  • 3. What is SQL? • Structured Query Language (SQL) is a standardized language used to manipulate database objects and the data they contain. • It comprised of several different statements that are used manipulate data values. • SQL being a nonprocedural is not a general-purpose programming language. UPDATE EMPLOYEE SET LASTNAME = 'Jones' WHERE EMPID = '001'
  • 4. What is Embedded SQL? • As a result, database applications are usually developed by combining capabilities of a high-level programming language with SQL. • The simplest approach is to embed SQL statements directly into the source code file(s) that will be used to create an application. This technique is referred to as embedded SQL programming. • sqlca.h – header file to be included.
  • 5. Embedded SQL • High-level programming language compilers cannot interpret, SQL statements. • Hence source code files containing embedded SQL statements must be preprocessed before compiling. • Thus each SQL statement coded in a high-level programming language source code file must be prefixed with the keywords EXEC SQL and terminated with either a semicolon or the keywords END_EXEC.
  • 6. Embedded SQL • Likewise, the Database Manager cannot work directly with high-level programming language variables. • Instead, it must use special variables known as host variables to move data between an application and a database. • Two types of Host variables:- 1. Input Host Variables – Transfer data to database 2. Output Host Variables – receives data from database
  • 7. Embedded SQL • Host variables are ordinary programming language variables. • To be set apart, they must be defined within a special section known as a declare section. EXEC SQL BEGIN DECLARE SECTION char EmployeeID[7]; double Salary; EXEC SQL END DECLARE SECTION • Each host variable must be assigned a unique name even though declared in different declaration section.
  • 8. Embedded SQL main() { EXEC SQL BEGIN DECLARE SECTION; int OrderID, CustID; char SalesPerson[10], Status[6]; EXEC SQL END DECLARE SECTION; printf ("Enter order number: "); scanf ("%d", &OrderID); EXEC SQL SELECT CustID, SalesPerson, Status FROM Orders WHERE OrderID = :OrderID INTO :CustID, :SalesPerson, :Status; printf ("Customer number: %d n", CustID); printf ("Salesperson: %s n", SalesPerson); printf ("Status: %s n", Status); }
  • 9. Embedded SQL Connecting to Database using embedded sql EXEC SQL CONNECT :userid IDENTIFIED BY :passwd; EXEC SQL CREATE TABLE Test (a int); EXEC SQL INSERT INTO Test VALUES (1); EXEC SQL SELECT MAX (a) INTO :value from R; printf (“Max value=%dn”,value);
  • 10. Cursor • Can declare a cursor on a query statement which generates a relation. • Can open a cursor, repeatedly fetch a tuple, move the cursor, until all tuples have been retrieved. • Control order: ORDER BY, in queries that are accessed through a cursor • Can also modify/delete tuple pointed to by cursor. • Must close cursor at end.
  • 11. Cursor EXEC SQL DECLARE myCursor CURSOR FOR SELECT bid from Reservations; EXEC SQL OPEN myCursor; EXEC SQL WHENEVER NOT FOUND DO break; while (1) { EXEC SQL FETCH myCursor INTO :num; } EXEC SQL CLOSE myCursor;
  • 12. Dynamic SQL • Dynamic SQL means composing and executing new (not previously compiled) SQL statements at run-time. • Although static SQL statements are relatively easy to incorporate, Dynamic SQL statements are much more flexible as they can be constructed at run time. • Dynamic queries can be complex because the type and number of retrieved attributes are unknown at compile time. INSERT INTO EMPLOYEES VALUES (?, ?) DELETE FROM DEPARTMENT WHERE DEPTID = ?
  • 13. SQLJ • SQLJ – Standard for embedding SQL in Java • Similar to existing SQL extensions provided for C, FORTRAN, and other programming languages. • IBM, Oracle, and several other companies proposed SQLJ as a standard and as a simpler and easier-to-use alternative to JDBC. • An SQLJ translator converts SQL statements into Java • These are executed through the JDBC interface • Certain classes have to be imported E.g., java.sql
  • 14. SQLJ • SQLJ precompiles SQL code in a Java program. • Provides greater compile-time checking of SQL statements. • Reduces the amount of code needed to execute SQL from within Java.
  • 15. SQLJ v/s JDBC // SQLJ int n; #sql { INSERT INTO emp VALUES (:n)}; // JDBC int n; Statement stmt = conn.prepareStatement (“INSERT INTO emp VALUES (?)”); stmt.setInt(1,n); stmt.execute (); stmt.close();
  • 16. class X { void myJavaMethod() { try { #sql{update EMP set SAL = SAL + 100 where SAL < 1500}; } SQLJ import java.sql.*; import sqlj.runtime.*; import sqlj.runtime.ref.*; Imports Needed SQL statement placed in braces can throw SQLException catch (SQLException e) {…} }
  • 17. SQLJ Loading the JDBC Driver 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 driver"); }
  • 18. SQLJ Specifying a Connection Context • All SQLJ statements execute in a “connection context” • Plays similar role as a Connection object does in JDBC. • Establishes the database we are connecting to, the user name, and the password. try { Class.forName("oracle.jdbc.driver.OracleDriver"); DefaultContext.setDefaultContext(new DefaultContext( "jdbc:oracle:thin:@HOSTID:1521:ORCL", "theUser", "thePassword") ); }
  • 19. SQLJ Passing Host Variables into a SQLJ Statement • Prefix the java variable name with a colon (:) #sql {delete from EMP where SAL >= :amt};
  • 20. SQLJ 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 that specifies the data type of each column #sql iterator MyIter(String ENAME, String JOB); class MyClass { MyIter iter; #sql iter = { select ENAME, JOB from EMP }; while(iter.next()) { String ename = iter.ENAME(); String job = iter.JOB(); }
  • 21. When to Which ? How do applications connect to a database? • App ↔ DBMS: Embedded SQL • App ↔ Driver ↔ DBMS: JDBC/ODBC or SQLJ What mechanisms exist to retrieve/modify data? • Static Queries: Embedded SQL, SQLJ • Dynamic Queries: JDBC/ODBC, Dynamic SQL

Editor's Notes

  1. 1
  2. Structured Query Language (SQL) is a standardized language used to manipulate database objects and the data they contain. SQL is comprised of several different statements that are used to define, alter, and destroy database objects, as well as add, update, delete, and retrieve data values. However, SQL is nonprocedural, and therefore is not a general-purpose programming language. (SQL statements are executed by the DB2 Database Manager, not by the operating system.) As a result, database applications are usually developed by combining the decision and sequence control of a high-level programming language with the data storage, manipulation, and retrieval capabilities of SQL. Several methods are available for merging SQL with a high-level programming language, but the simplest approach is to embed SQL statements directly into the source code file(s) that will be used to create an application. This technique is referred to as embedded SQL programming.
  3. When the preprocessor (a special tool known as the SQL precompiler) encounters these keywords, it replaces the text that follows (until a semicolon (;) or the keywords END-EXEC is found) with a DB2 UDB-specific function call that forwards the specified SQL statement to the DB2 Database Manager for processing.
  4. Host variables that transfer data to a database are known as input host variables, while host variables that receive data from a database are known as output host variables. Regardless of whether a host variable is used for input or output, its attributes must be appropriate for the context in which it is used. Therefore, you must define host variables in such a way that their data types and lengths are compatible with the data types and lengths of the columns they are intended to work with
  5. A declare section can be coded anywhere high-level programming language variable declarations can be coded in a source code file. Although a source code file typically contains only one declare section, multiple declare sections are allowed.
  6. a program accepts SQL statements from the keyboard at run-time. Generally, dynamic SQL statements are well suited for applications that interact with a rapidly changing database or that allow users to define and execute ad-hoc queries.
  7. JDBC is an API that enables database access from Java programs
  8. SQLJ is passed through a precompiler Checks SQL against the database Generates Java code with JDBC calls
  9. JDBC needs: explicit statement handles explicit setXxx binds explicit connection
  10. JDBC is an API that enables database access from Java programs
  11. JDBC is an API that enables database access from Java programs
  12. JDBC is an API that enables database access from Java programs
  13. JDBC is an API that enables database access from Java programs