Embedded SQL is a method of combining the computing power of a programming language and the database manipulation capabilities of SQL.
Here’s the high level idea:
Commands
Here are the different command types that you can simply plug into your C++ code
At the top of your main function, you need to Include SQL Communication Area:
EXEC SQL INCLUDE SQLCA;
SQLCA
SQLCA stands for SQL Communications Area. It is a data structure used in programming with Embedded SQL, which is a way of embedding SQL statements within a high-level programming language such as C or COBOL.
Host Variables
SQL statements can have parameters that are local or global variables in the embedding language.
You can then use them in EXEC SQL statements. To distinguish them from SQL identifiers, they are prefixed by :. For example,
Exception Handling
if a SQL statement fails, you can either check sqlcode != 0, or use exceptional handling SQL commands:
Note that <label> must be in scope.
Full Example sample1.sqc:
More Advanced Example, storing data
Notice a few things:
use the INTO keyword to store into variable
“Write a program that prints out the title of the publication for each publication identifier supplied as an argument”.
DANGER!
It is important here that at most ONE title is returned for each publication identifier.
Then, you can run
It should print out:
Sample C program: SAMPLE2
Connected to DB2
1: Mathematical Logic
7: *** not found ***
3: Principles of DB Systems
5: *** not found ***
SQL Cursor
For SQL queries possibly returning more than one answer, an SQL CURSOR is defined and used in an iterator protocol.
Declaring a cursor:
An iterator protocol using a cursor:
“Write a program that lists all author names and publication titles with author name matching a pattern given as an argument”.
Execution:
Preparing the Application in DB2
How much does the DBMS know about an application?
⇒ precompiling: PREP
⇒ binding: BIND
Steps:
Write the application in a file called <name>.sqc
Preprocess the application: db2 prep <name>.sqc
Compile the application: cc -c -O <name>.c
Link with DB2 libraries: cc -o <name> <name.o> -L... -l...
Run it: ./<name> [arguments]
In practice, the above steps is done with a Makefile.