DBMS - Unit 3 - Notes (Embedded & Dynamic SQL)
DBMS - Unit 3 - Notes (Embedded & Dynamic SQL)
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
6
HOST LANGUAGE PROGRAMS WITH SQL
Preprocessor
Host
Hostlanguage
languagecompiler
compiler
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.
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);
}