Download presentation
Presentation is loading. Please wait.
Published byJayson Fox Modified over 8 years ago
1
Lu Wei1 Outline Introduction Basic SQL Setting Up and Using PostgreSQL Advanced SQL Embeded SQL
2
Lu Wei2 Embeded SQL Introduction SQL Communications Area Host Language Varibles Cursors Static Embedded SQL Statements Dynamic SQL ODBC
3
Lu Wei3 Introduction We mentioned in chapter 3 that SQL can be used in two ways: –Use SQL interactively by entering the statements at a terminal –Embed SQL statements in a procedural language (programmatic SQL)
4
Lu Wei4 Introduction In fact, we can distinguish between two types of programmic SQL –Embeded SQL statements SQL statements are embeded directly into the program source code and mixed with the host language statements. Need to be precompiled. –Application Programming Interface (API) Provide the programmer with a standard set of functions that can be invoked from the software. Need not to be precompiled. Open Database Connectivity (ODBC) standard.
5
Lu Wei5 SQL Communications Area The DBMS uses an SQL Communications Area (SQLCA) to report runtime errors to the application program. SQLCA is a data structure that contains error variables and status indicators. An application program can examine the SQLCA to determine the success or failure of each SQL statement.
6
Lu Wei6 SQL Communications Area Definition of the SQLCA for Oracle. /** NAME SQLCA: SQL Communication Area. FUNCTION Contains no code. Oracle fills in the SQLCA with status info during the execution of an SQL statement. **/
7
Lu Wei7 SQL Communications Area struct sqlca{ char sqlcaid[8]; //contains fixed text “SQLCA” long sqlcabc; //length of SQLCA structure long sqlcode; //SQL return code struct{ short sqlerrml; //length of error message char sqlerrmc[70]; //text of error message } sqlerrm; char sqlerrp[8]; //reserved for future use long sqlerrd[6]; //sqlerrd[2]-number of rows processed char sqlwarn[8];
8
Lu Wei8 SQL Communications Area //sqlwarn[0] set to “W” on warning //sqlwarn[1] set to “W” if character string truncated //sqlwarn[2] set to “W” if NULLs eliminated from aggregates //sqlwarn[3] set to “W” if mismatch in columns/host variables //sqlwarn[4] set to “W” when preparing an update/delete without a where-clause //sqlwarn[5] set to “W” due to PL/SQL compilation failure //sqlwarn[6] no longer used //sqlwarn[7] no longer used char sqlext[8]; //reserved for furture use }
9
Lu Wei9 SQL Communications Area The SQLCODE is set by the DBMS as follows: –0 indicates that the statement executed successfully (although there may be warning messages in sqlwarn) –A negative value indicates that an error occurred. The value in SQLCODE indicates the specific error that occurred. –A positive value indicates that the statement executed successfully, but an exceptional condition occurred, such as no more rows returned by a SELECT statement.
10
Lu Wei10 SQL Communications Area The WHENEVER statement –Every embedded SQL statement can potentially generate an error. Clearly, checking for success after every SQL statement would be quite laborious. –Oracle precompiler provides an alternative method to simplify error handling. –The format of the WHENEVER statement is EXEC SQL WHENEVER
11
Lu Wei11 SQL Communications Area Condition -SQLERROR(SQLCODE<0) -SQLWARNING(SQLCODE>0) -NOT FOUND Action -CONTINUE -DO, DO BREAK, DO CONTINUE -GO TO label -STOP
12
Lu Wei12 Host Language Varibles A host language variable is a program variable declared in the host language. It can be either a single variable or a structure. Host language variables can be used in embedded SQL statements to transfer data from the database into the program, and vice versa.
13
Lu Wei13 Host Language Varibles To use a host variable in an embedded SQL statement, the variable name is prefixed by a colon(;). Example EXEC SQL UPDATE Staff SET salary = salary + :increment WHERE staffNo=‘SL21’;
14
Lu Wei14 Host Language Varibles Host language variables must be declared to SQL as well as being declared in the syntax of the host language. All host variables must be declared to SQL in a BEGIN DECLARE SECTION…END DECLARE SECTION block. EXEC SQL BEGIN DECLARE SECTION; float increment; EXEC SQL END DECLARE SECTION;
15
Lu Wei15 Host Language Varibles Indicator variables –Most programming languages do not provide support for unknown or missing values, as represented in the relational model by nulls. –Embedded SQL provides indicator variables to resolve this problem.
16
Lu Wei16 Host Language Varibles The meaning of the indicator variable is as follows: –A 0 value means that the associated host variable contains a valid value. –A -1 value means that the associated host variable should be assumed to contain a null(the actual content of the host variable is irrelevant). –A positive indicator value means that the associated host variable contains a valid value, which may have been rounded or truncated.
17
Lu Wei17 Host Language Varibles Example EXEC SQL BEGIN DECLARE SECTION; char address[51]; short addressInd; EXEC SQL END DECLARE SECTION; addressInd = -1; EXEC SQL UPDATE privateOwner SET address =:address :addressInd WHERE ownerNo = ‘CO21’;
18
Lu Wei18 Cursors We can also retrieve data using the SELECT statement, but the processing is more complicated if the query produces more than one row. The complication results from the fact that most high-level programming languages can process only individual data items or individual rows of a structure whereas SQL process multiple rows of data.
19
Lu Wei19 Cursors To overcome this impedance mismatch, SQL provides a mechanism for allowing the host language to access the rows of a query result one at a time. Embedded SQL divides queries into two groups: –Single-row queries –Multi-row queries
20
Lu Wei20 Cursors Single-row queries –example1
21
Lu Wei21 Cursors Multi-row queries –example2
22
Lu Wei22 Static Embedded SQL Statements In static embedded SQL statement, the pattern of database access is fixed and can be ‘hard- coded’ into the program. Static SQL does not allow host variables to be used in place of table names or column names. The embedded SQLs we discussed above are all static SQLs.
23
Lu Wei23 Static Embedded SQL Statements In static Embedded SQL, the follow elements must be fixed: –Reserved words (SELECT,UPDATE,DELETE…) –The number of host variables –The data type of each host variable –The database object will be accessed in SQL(table,column,view,index,…) Or dynamic SQL will be used.
24
Lu Wei24 Dynamic SQL In many situations where the pattern of database access is not fixed and is known only at runtime. This requires more flexibility than static SQL. Dynamic embedded SQL can be used to resolve this problem.
25
Lu Wei25 Dynamic SQL The basic idea of dynamic SQL is to place the complete SQL statement to be executed in a host variable. The host variable is then passed to the DBMS to be executed.
26
Lu Wei26 Dynamic SQL EXECUTE IMMEDIATE statement EXEC SQL EXECUTE IMMEDIATE [hostVariable|stringLiteral];
27
Lu Wei27 Dynamic SQL EXEC SQL BEGIN DECLARE SECTION; float increment; EXEC SQL END DECLARE SECTION; EXEC SQL UPDATE Staff SET salary=salary+:increment WHERE staffNo=‘SL21’;
28
Lu Wei28 Dynamic SQL EXEC SQL BEGIN DECLARE SECTION; char buffer[100]; EXEC SQL END DECLARE SECTION; sprintf(buffer,”UPDATE Staff SET salary=salary+%f WHERE staffNo=‘SL21’”,increment;); EXEC SQL EXECUTE IMMEDIATE :buffer;
29
Lu Wei29 Dynamic SQL The PREPARE and EXECUTE Statements PrecompilerBind utilityExecute Compile timeRun time ( a ) static SQL Run time EXECUTE IMMEDIATE statement PREPARE statement EXECUTE Parse statement Validate statement Optimize statement Create execute plan Execute statement ( b )动态 SQL
30
Lu Wei30 Dynamic SQL The format of the PREPARE statement The format of the EXECUTE statement EXEC SQL PREPARE statementName FROM [hostVariable|stringLiteral] EXEC SQL EXECUTE statementName [USING hostVariable[indicatorVariable][,…]| USING DESCRIPTOR descriptorName]
31
Lu Wei31 Dynamic SQL EXEC SQL BEGIN DECLARE SECTION; char buffer[100]; float newSalary; char staffNo[6]; EXEC SQL END DECLARE SECTION; SPRINTF(buffer,”update staff set salary=:sal where staffNo=:sn”); EXEC SQL PREPARE stmt FROM :buffer;
32
Lu Wei32 Dynamic SQL do{ printf(“Enter staff number:”); scanf(“%s”,staffNo); printf(“Enter new salary:”); scanf(“%f”,newSalary); EXEC SQL EXECUTE stmt USING :newSalary,:staffNo; printf(“Enter another(Y/N)?”); scanf(“%c”,nore); } until(more!=‘Y’);
33
Lu Wei33 Dynamic SQL Example3
34
Lu Wei34 Dynamic SQL The SQL Descriptor Area –Placeholders are one way to pass parameters to the EXECUTE statement. –An alternative is through a dynamic data structure called the SQL Descriptor Area(SQLDA) –The SQLDA is used when the number of placeholders and their data types are not known when the statement is formulated.
35
Lu Wei35 ODBC
36
Lu Wei36 Summary How SQL statements can be embedded in high- level programming languages. The difference between static and dynamic embedded SQL How to write programs that use static or dynamic embedded SQL statements How to use ODBC to connect to database.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.