09 SQLProgramming
09 SQLProgramming
For this section, we will deal with the interaction between the
application and the DBMS
Environments, Connections, Queries
A SQP environment is the framework under which data exists and SQL
operations are executed.
Think of a SQL environment as a DBMS running at some installation.
So tables, triggers, views, etc are defined within a SQL environment
Database servers maintain some number of connections, so app servers
can ask queries or perform modifications.
The app server issues statements: queries and modifications, usually.
Diagramatically
Environment
Connection
Statement
The SQL/Host Language Interface:
Options
SELECT-INTO: used
for a single row
Embedded Queries
Embedded SQL (so far) has a limitation regarding queries:
SELECT-INTO for a query guaranteed to produce a single tuple.
Otherwise, you have to use a cursor.
Recall: A cursor is essentially a tuple-variable that ranges over all
tuples in the result of some query.
Using a cursor lets one iterate through tuples satisfying a query.
Cursor Statements
Declare a cursor c with:
EXEC SQL DECLARE c CURSOR FOR <query>;
Open and close cursor c with:
EXEC SQL OPEN CURSOR c;
EXEC SQL CLOSE CURSOR c;
The OPEN statement causes the query to be evaluated.
The CLOSE statement causes the database to delete the temporary
relation that holds the result of the query.
Fetch from c by:
EXEC SQL FETCH c INTO <variable(s)>;
Repeated calls to FETCH get successive tuples in the query result.
Macro NOT FOUND is true if and only if the FETCH fails to find a
tuple.
Example Cursor
From within a host language, want to find the names and cities of
customers with more than the variable amount dollars in some
account.
while(1) {
/* issue SQL> prompt */
/* read user’s query into array query */
EXEC SQL PREPARE q FROM :query;
EXEC SQL EXECUTE q; q is an SQL variable
} representing the
optimized form of
whatever statement
is typed into :query
Execute-Immediate
If we are only going to execute the query once, we can combine the
PREPARE and EXECUTE steps into one.
Use:
EXEC SQL EXECUTE IMMEDIATE <text>;
Example: Generic Interface Again
EXEC SQL BEGIN DECLARE SECTION;
char query[MAX_LENGTH];
EXEC SQL END DECLARE SECTION;
while(1) {
/* issue SQL> prompt */
/* read user’s query into array query */
EXEC SQL EXECUTE IMMEDIATE :query;
}
Another Example
Example of the use of dynamic SQL from within a C program.