Sunteți pe pagina 1din 23

SQL: A COMMERCIAL DATABASE LANGUAGE

Database Programming/ Using SQL in an Application

Outline
1. Introduction 2. Data Definition, Basic Constraints, and Schema Changes 3. Basic Queries 4. More complex Queries 5. Aggregate Functions and Grouping 6. Advanced Querying Issues 7. Summary of SQL Queries 8. Data Change statements 9. Views 10. Complex Constraints 11. Database Programming

10.1 Motivation (1)


Up to now we have seen SQL as an interactive language: we type a query and see the results on the screen. We are interested in creating programs that involve a mixture of SQL statements, and statements from a conventional language. The SQL statements will enable the program to access the database. The conventional language, called the host language, will supply features that are unavailable to SQL (e.g. control mechanisms such as if and while statements, assignment statements and error handling).

10.1 Motivation (2)


In most SQL applications, SQL statements are part of an application program written in some conventional language such as C, Cobol, Java or Visual Basic. We discuss some advanced features of SQL that address the issues involved in this type of execution.

10.2 Issues Involved (1)


SQL constructs can be included in an application program in two different ways: through a Statement-Level Interface (SLI), or a Call-Level Interface (CLI).

10.2 Issues Involved (2)


Statement-Level Interface (SLI). The SQL constructs appear as new statement types in the program. The program is a mixture of two statement types: the host language and the new statement types. Before the program can be compiled by the host language compiler, the SQL constructs must be processed by a precompiler, which translates the constructs into calls to host language procedures. The entire program can then be compiled by the host language compiler. At run time, the created host language procedures communicate with the DBMS, which takes the actions necessary to cause the SQL statements to be executed.

10.2 Issues Involved (3)


Statement-Level Interface (SLI). The SQL constructs can take two forms: - Embedded SQL: the SQL constructs are ordinary SQL statements (e.g. SELECT, INSERT). Embedded SQL is also referred to as Static SQL. - Dynamic SQL: the SQL constructs are directives for preparing and executing SQL statements, but the SQL statements appear in the program as the values of string variables that are constructed by the host language portion of the program at run time. SQLJ a version of SLI designed specifically for Java was standardized in SQL:2003.

10.2 Issues Involved (4)


Call-Level Interface (CLI). Unlike Static and Dynamic SQL, the application program is written entirely in the host language. As with Dynamic SQL, SQL statements are the values of string variables constructed at run time. These variables are passed as arguments to host language procedures provided by the CLI. Since no special syntax is used, no precompiler is needed. JDBC (Java DataBase Connectivity), is a CLI specifically designed for Java (SQL:2003) and ODBC (Open DataBase Connectivity), is a CLI that can be used with many languages (SQL:1999).

10.3 Embedded SQL


The embedded SQL statement is distinguished from programming language statements by prefixing it with a special character or command so that a preprocessor can extract the SQL statements. Usually, the keywords EXEC SQL precede any SQL statement. We will use pseudocode as the host programming language. Within an embedded SQL command, we may refer to host program variables, which are prefixed by a : sign. The programmer should declare program variables to match the data types of the database attributes that the program will process. These program variables may or may not have names that are identical to their corresponding attributes.

10.4 Status Processing (1)


In the real world, things do not always proceed smoothly. For example, when you attempt to connect to a database on a distant server, the server might be down or reject the connection. In other situations, an SQL statement may execute correctly and return the outcome of the execution.

SQL provides two mechanisms for returning information describing such situations to the host program: a five character string variable SQLSTATE and a diagnostics area.

10.4 Status Processing (2)


An implicit five-character string variable SQLSTATE communicates to the program the status of SQL embedded commands.

The DBMS sends information to be stored in that variable after each SQL statement is executed.

If the value of SQLSTATE is 00000, the last statement executed successfully. If not, the particular exception situation can be determined, and appropriate action can be taken.

10.4 Status Processing (3)


Instead of checking status after each SQL statement, we can include a single WHENEVER statement anywhere before the first SQL statement is executed: EXEC SQL WHENEVER SQLERROR GOTO label; Then, any nonzero status in a subsequently executed statement causes a transfer of control to label. The WHENEVER statement remains in effect until another statement is executed.

10.4 Status Processing (4)


The diagnostics area is a data structure that contains information about the execution status of the most recent SQL statement. A single SQL statement may raise several exceptions. The diagnostics area records information about all exceptions raised. Detailed information about the outcome of the last executed SQL statement can be retrieved from the diagnostics area using a GET DIAGNOSTICS statement.

10.5 Variable declaration (1)


For the application program as a whole to communicate with the database, host language statements and SQL statements must be able to access common variables. In that way: - results computed by the host language portion of the program can be stored in the database, and - data extracted from the database can be processed by the host language statements. Before the embedded SQL statements, we declare variables of the host program (host variables) that are used for this purpose. The declarations are included between EXEC SQL BEGIN DECLARE SECTION, and EXEC SQL END DECLARE SECTION so that they can be easily found and processed by the precompiler.

10.5 Variable declaration (2)


Example: The following group of statements declares variables of the host program. EXEC SQL BEGIN DECLARE SECTION varchar dname [16], fname [16], lname [16], address [31]; char ssn [10], bdate [11], sex [2], minit [2]; float salary, raise; int dno, dnumber; char SQLSTATE [6]; EXEC SQL END DECLARE SECTION SQLSTATE is declared within the declaration section since it is used for communication between the DMBS and the host language portion of the application. This declaration is required in all embedded SQL programs.

10.6 Single row statements (1)


Example: Write a program segment (loop) that reads a social security number and prints out some information from the corresponding EMPLOYEE tuple
loop:= 'Y'; while loop = 'Y' do begin writeln('input social security number:'); readln(SSN); EXEC SQL SELECT FNAME, MINIT, LNAME, BDATE, ADDRESS, SALARY INTO :fname, :minit, :lname, :bdate, :address, :salary FROM EMPLOYEE WHERE SSN = :ssn ; if SQLSTATE = 00000 then writeln(fname, minit, lname, address, salary) else writeln(ssn does not exist); writeln('more SS numbers (Y or N)? '); readln(loop) end;

10.6 Single row statements (2)


We can think of the host language variables as parameterizing the SQL statement. They are used to communicate scalar values, not table or column names or structured data. Host variables that occur in WHERE clauses correspond to in parameters, while those used in INTO clauses correspond to out parameters.

10.7 Cursors (1)


In the previous program segment, a single tuple is selected by the embedded SQL query; that is why we are able to assign its attribute values directly to program variables. In general, an SQL query can retrieve many tuples. One of the advantages of SQL as a database language is that its statements can deal with entire tables. An SQL query returns a table which we refer to as the query result or result set. If we want to include an SQL SELECT statement in a host language program, the number of rows in the result set in not know until the statement is executed. Thus, we face the problem of allocating storage within the program for an unknown number of rows.

10.7 Cursors (2)


This problem points up a fundamental difference between SQL and the host language: - the fundamental unit dealt with by an SQL statement is a set of tuples, whereas - the fundamental unit dealt with by a statement in a host language is a variable. This difference is often called an impedance mismatch. The SQL mechanism for solving this problem is the cursor. It allows a tuple-at-a-time processing or a query set by the host program.

10.7 Cursors (3)


We can think of a cursor as a pointer that points to a single tuple (row) from the result of a query. The cursor is declared when the SQL query command is specified. A subsequent OPEN cursor command fetches the query result and sets the cursor to a position before the first row in the result of the query; this becomes the current row for the cursor. Subsequent FETCH commands in the program advance the cursor to the next row and copy its attribute values into program variables specified in the FETCH command.

10.7 Cursors (4)


- A CLOSE cursor command is issued to indicate that we are done with the result of the query. - When a cursor is defined for rows that are to be updated the clause FOR UPDATE OF must be in the cursor declaration, and a list of the names of any attributes that will be updated follows. - The condition WHERE CURRENT OF cursor specifies that the current tuple is the one to be updated (or deleted) Example: Write a program segment that reads (inputs) a department name, then lists the names of employees who work in that department, one at a time. The program reads a raise amount for each employee and updates the employee's salary by that amount.

10.7 Cursors (5)


writeln('enter the department name:'); readln(DNAME); EXEC SQL SELECT DNUMBER INTO :dnumber FROM DEPARTMENT WHERE DNAME =: dname; EXEC SQL DECLARE EMP CURSOR FOR SELECT SSN, FNAME, MINIT, LNAME, SALARY FROM EMPLOYEE WHERE DNO =: dnumber FOR UPDATE OF SALARY; EXEC SQL OPEN EMP; EXEC SQL FETCH EMP INTO :ssn, :fname, :minit, :lname, :salary;

10.7 Cursors (6)


while SQLSTATE = '00000' do begin writeln('employee name: ', fname, minit,lname); writeln('enter raise amount: '); readln(raise); EXEC SQL UPDATE EMPLOYEE SET SALARY = SALARY + :raise WHERE CURRENT OF EMP; EXEC SQL FETCH EMP INTO :ssn, :fname, :minit, :lname, :salary; end; EXEC SQL CLOSE CURSOR EMP;

S-ar putea să vă placă și