0% found this document useful (0 votes)
938 views

DBMS - Unit 3 - Notes (Embedded & Dynamic SQL)

Embedded SQL is a method of combining SQL statements with a host programming language like C/C++. With embedded SQL, SQL statements are written directly into the source code of the host language. At compile time, a preprocessor extracts the SQL statements and replaces them with function calls. This allows SQL capabilities to be added to any programming language. Embedded SQL statements are static - the SQL must be known at compile time. Dynamic SQL builds SQL statements dynamically at runtime based on user input. It uses functions like PREPARE to build the SQL string and EXECUTE to execute the prepared statement.

Uploaded by

ABC
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
938 views

DBMS - Unit 3 - Notes (Embedded & Dynamic SQL)

Embedded SQL is a method of combining SQL statements with a host programming language like C/C++. With embedded SQL, SQL statements are written directly into the source code of the host language. At compile time, a preprocessor extracts the SQL statements and replaces them with function calls. This allows SQL capabilities to be added to any programming language. Embedded SQL statements are static - the SQL must be known at compile time. Dynamic SQL builds SQL statements dynamically at runtime based on user input. It uses functions like PREPARE to build the SQL string and EXECUTE to execute the prepared statement.

Uploaded by

ABC
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

EMBEDDED AND DYNAMIC SQL

What is Embedded SQL (Static)?


 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.
EMBEDDED SQL
 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, etc.
 When SQL is embedded within C language, the compiler
processes the compilation in two steps. It first extracts all the SQL
codes from the program and the pre-compiler will compile the
SQL code for its syntax, correctness, execution path etc.
 Once pre-compilation is done, these executable codes are
embedded into the C code. Then the C compiler will compile
the code and execute the code. Thus the compilation takes
place in two steps – one for SQL and one for application
3

language.
Hence these types of compilation require all the query,
data value etc to be known at the compilation time itself
to generate the executable code. Hence the SQL codes
written are static and these embedded SQL is also known
as Static SQL.
This is very important as pre-compiler will first extract all
the SQLs embedded in it to compile it at DB level. Then it
will be embedded in the C code which will be compiled
by the C compiler to get executable code.
All
the embedded SQLs are preceded by keyword ‘EXEC
SQL’ and ends in semicolon (;) or END_EXEC. We can
have these SQLs placed anywhere in the host language
4

code.
 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:-
• Input Host Variables – Transfer data to database
• Output Host Variables – receives data from database
CONNECTING SQL TO THE HOST LANGUAGE

1. Embedded SQL is a standard for combining SQL


with seven languages.
2. CLI (Call-Level Interface ) is a different approach
to connecting C to an SQL database.
3. JDBC (Java Database Connectivity ) is a way to
connect Java with an SQL database.

6
HOST LANGUAGE PROGRAMS WITH SQL

Host language + Embedded SQL

Preprocessor

Host Language + function calls

Host
Hostlanguage
languagecompiler
compiler

Host language program


CONNECTING SQL TO THE HOST LANGUAGE
Declaration Section
 Once connection is established with DB, query will be written
and executed. Similarly, results of DB query will be returned to
the host language which will be captured by the variables of
host language. Hence we need to declare the variables to
pass the value to the query and get the values from query.
There are two types of variables used in the host language.
 Hostvariable : These are the variables of host language used
to pass the value to the query as well as to capture the values
returned by the query.
 BEGIN DECLARE and END DECLARE section. Again, these 8
declare block should be enclosed within EXEC SQL and ‘;’.
Indicator Variable : These variables are also host
variables but are of 2 byte short type always. These
variables are used to capture the NULL values that
a query returns or to INSERT/ UPDATE any NULL
values to the tables. When it is used in a SELECT
query, it captures any NULL value returned for any
column. When used along with INSERT or UPDATE, it
sets the column value as NULL, even though the
host variable has value. If we have to capture the
NULL values for each host variable in the code,
then we have to declare indicator variables to
each of the host variables. 9
Execution Section
This is the execution section, and it contains all the SQL
queries and statements prefixed by ‘EXEC SQL’.

EXEC SQL SELECT * FROM STUDENT WHERE STUDENT_ID


=:STD_ID;

In this embedded SQL, all the queries are dependent on


the values of host variable and queries are static. In
above example of SELECT query, it always pulls student
details for the student Id inserted. But suppose user enters
student name instead of student ID. Then these SQLs are
not flexible to modify the query to fetch details based on
name.
Error Handling
 Errorhandling method would be based on the host language. Here we
are using C language and we use labeling method, i.e.; when error
occurs we stop the current sequence of execution and ask the compiler
to jump to error handling section of the code to continue.
 This structure is known as SQL Communication Area or SQLCA.
EXEC SQL WHENEVER condition action;
The condition in WHENEVER clause can be
 SQLWARNING – indicates SQL warning. It indicates the compiler that
when SQL warning occurs perform action.
 SQLERROR – indicates SQL Error. The SQLCODE will have negative value.
 NOT FOUND - SQLCODE will have positive value indicating no records are
fetched.
11
 SQLSTATE - A special variable SQLSTATE provides a 5-digit code
indicating the status of the operation (e.g., 00000 says that the
operation completed with no problem).

On receiving error or warning, action can be any one of the following:


 CONTINUE – indicates to continue with the normal execution of the
code.
 DO – it calls a function and hence program will move to execute this
error handling function.
 GOTO <label> - Program will jump to the location <label> to execute
error handling.
 STOP – it immediately stops the execution of the program by calling
exit (0) and all the incomplete transactions will be rolled back.
EMBEDDED SQL PROGRAM
#include <stdio.h>
#include <sqlca.h>
int main(){
EXEC SQL INCLUDE SQLCA;

EXEC SQL BEGIN DECLARE SECTION;


BASED ON STUDENT.STD_ID SID;
char *STD_NAME;
short ind_sid;
EXEC SQL END DECLARE SECTION;
13
//Error handling
EXEC SQL WHENEVER NOT FOUND GOTO error_msg1;
EXEC SQL WHENEVER SQLERROR GOTO error_msg2;
printf("Enter the Student name:");
scanf("%s", STD_Name);
// Executes the query
EXEC SQL SELECT STD_ID INTO :SID INDICATOR ind_sid FROM
STUDENT WHERE STD_NAME = :STD_NAME;
printf("STUDENT ID:%d", STD_ID); // prints the result from DB
exit(0); 14
// Error handling labels
error_msg1:
printf("Student Id %d is not found",
STD_ID);
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0);
error_msg2:
printf("Error has occurred!");
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0); 15
DYNAMIC SQL
 Dynamic SQL is a programming technique that enables
you to build SQL statements dynamically at runtime. You
can create more general purpose, flexible applications
by using dynamic SQL because the full text of a SQL
statement may be unknown at compilation.
 Dynamic SQL programs can handle changes in data
definitions, without the need to recompile.
 If we need to build up queries at run time, then we can
use dynamic sql. That means if query changes according
to user input, then it always better to use dynamic SQL.
In dynamic SQL, queries are created, compiled and
executed only at the run time. This makes the dynamic
SQL little complex, and time consuming.

PREPARE
Dynamic SQL builds a query at run time, as a first step we
need to capture all the inputs from the user. It will be
stored in a string variable. Depending on the inputs
received from the user, string variable is appended with
inputs and SQL keywords. These SQL like string statements
are then converted into SQL query. This is done by using
PREPARE statement.
EXAMPLE
sql_stmt = "SELECT STD_ID FROM STUDENT ";
if (strcmp(STD_NAME, '') != 0){
sql_stmt = sql_stmt || " WHERE STD_NAME = :STD_NAME";
}
else if (CLASS_ID > 0){
sql_stmt = sql_stmt || " WHERE CLASS_ID = :CLASS_ID";
EXEC SQL PREPARE sql_query FROM :sql_stmt

EXECUTE
This statement is used to compile and execute the SQL statements
prepared in DB.
EXEC SQL EXECUTE sql_query;
EXECUTE IMMEDIATE
This statement is used to prepare SQL statement as well as
execute the SQL statements in DB. It performs the task of
PREPARE and EXECUTE in a single line.

EXEC SQL EXECUTE IMMEDIATE : sql_stmt;


DYNAMIC SQL PROGRAM
#include <stdio.h>
#include <sqlca.h>
int main(){
EXEC SQL INCLUDE SQLCA ;
EXEC SQL BEGIN DECLARE SECTION;
int STD_ID;
char *STD_NAME;
int CLASS_ID;
char *sql_stmt;
char *sql_query;
EXEC SQL END DECLARE SECTION;

EXEC SQL WHENEVER NOT FOUND GOTO error_msg1;


EXEC SQL WHENEVER SQLERROR GOTO error_msg2;
printf("Enter the Student name:");
scanf("%s", STD_Name);
printf("Enter the Class ID:");
scanf("%d", &CLASS_ID);

sql_stmt = "SELECT STD_ID FROM STUDENT ";


if (strcmp(STD_NAME, '') != 0)
sql_stmt = sql_stmt || " WHERE STD_NAME =
:STD_NAME";
else if (CLASS_ID > 0)
sql_stmt = sql_stmt || " WHERE CLASS_ID =
:CLASS_ID";
if (strcmp(STD_NAME, '') !=0 && CLASS_ID >0)
sql_stmt = sql_stmt || " AND CLASS_ID = :CLASS_ID";
2
1
EXEC SQL PREPARE sql_query FROM :sql_stmt;
EXEC SQL EXECUTE sql_query;

printf("STUDENT ID:%d", STD_ID);


exit(0);

error_msg1:
printf("Student Id %d is not found", STD_ID);
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0);
error_msg2:
printf("Error has occurred!");
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0);
}

You might also like