programmatic sql

23
Programmatic SQL Programmatic SQL Shaista Khan Shaista Khan CS 157B CS 157B

Upload: byron

Post on 25-Jan-2016

115 views

Category:

Documents


1 download

DESCRIPTION

Programmatic SQL. Shaista Khan CS 157B. Topic. Embedded SQL statements in high-level programming languages. Why Embedded SQL?. SQL standard lacked “computational completeness”: it contained no flow of control commands such as IF, THEN, ELSE, GOTO, DO, or DO…WHILE. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Programmatic SQL

Programmatic SQLProgrammatic SQL

Shaista KhanShaista Khan

CS 157BCS 157B

Page 2: Programmatic SQL

TopicTopic

Embedded SQL statements in high-Embedded SQL statements in high-level programming languages.level programming languages.

Page 3: Programmatic SQL

Why Embedded SQL?Why Embedded SQL?

• SQL standard lacked “computational SQL standard lacked “computational completeness”: it contained no flow of completeness”: it contained no flow of control commands such as IF, THEN, control commands such as IF, THEN, ELSE, GOTO, DO, or DO…WHILE. ELSE, GOTO, DO, or DO…WHILE.

• To overcome this and to provide more To overcome this and to provide more flexibility, SQL allows statements to flexibility, SQL allows statements to be “embedded” in a high-level be “embedded” in a high-level procedural language.procedural language.

Page 4: Programmatic SQL

Two types of Programmatic Two types of Programmatic SQLSQL

• Embedded SQL statementsEmbedded SQL statements– SQL statements are embedded into the SQL statements are embedded into the

program source code and mixed with the host program source code and mixed with the host language statements. This allows users to write language statements. This allows users to write programs that access the database directly. A programs that access the database directly. A special precompiler modifies the source code special precompiler modifies the source code to replace SQL statements with calls to DBMS to replace SQL statements with calls to DBMS routines. The source code can then be routines. The source code can then be compiled and linked in the normal way.compiled and linked in the normal way.

• Application Programming Interface (API)Application Programming Interface (API)– No need for any precompilation.No need for any precompilation.– Provides a cleaner interface and generates more Provides a cleaner interface and generates more

manageable code.manageable code.

Page 5: Programmatic SQL

2 Types of Embedded SQL2 Types of Embedded SQL• Static SQLStatic SQL

– A complete embedded SQL statement. A complete embedded SQL statement. – Static SQL statements can be placed into Static SQL statements can be placed into

stored procedures and can contain host stored procedures and can contain host variables.variables.

• Dynamic SQLDynamic SQL– With dynamic SQL statements, knowing the With dynamic SQL statements, knowing the

complete structure of an SQL statement before complete structure of an SQL statement before building the application is not necessary. building the application is not necessary. Dynamic SQL statements allow run-time input Dynamic SQL statements allow run-time input to provide information about the database to provide information about the database objects to query.objects to query.

Page 6: Programmatic SQL

Simple SQL StatementSimple SQL Statement

CREATE TABLE Viewing (propertyNo VARCHAR2(5) NOT CREATE TABLE Viewing (propertyNo VARCHAR2(5) NOT NULL,NULL,

clientNo VARCHAR2(5) clientNo VARCHAR2(5) NOT NULL, NOT NULL,

viewDate DATEviewDate DATE NOT NOT NULL,NULL,

comments VARCHAR2(40));comments VARCHAR2(40));

Page 7: Programmatic SQL

Static SQLStatic SQL

/*Program to create the Viewing table*/#include <stdio.h>#include <stdlib.h>EXEC SQL INCLUDE sqlca;main(){

EXEC SQL BEGIN DECLARE SECTION;char *username = “Manager/Manager”;char *connectString = “DreamHome”;

EXEC SQL END DECLARE SECTION;/* Connect to database*/

EXEC SQL CONNECT :username USING :connectString;If(sqlca.sqlcode < 0) exit(-1);

/* Display message for user and create the table */printf (“Creating VIEWING table\n”);

EXEC SQL CREATE TABLE Viewing (propertyNo VARCHAR2(5) NOT NULL, clientNo VARCHAR2(5) NOT NULL,

viewDate DATE NOT NULL, comments VARCHAR2(40));

if (sqlca.sqlcode >= 0) /* Check success */printf (“Creation successful\n”);

elseprintf (“Creation unsuccessful\n”);

/* Commit the transaction and disconnect from the database */EXEC SQL COMMIT WORK RELEASE;

}

Page 8: Programmatic SQL

Using the SQLCA Data Using the SQLCA Data StructureStructure

• The SQL Communication Area (SQLCA) The SQL Communication Area (SQLCA) is a data structure that traps and is a data structure that traps and reports runtime errors to the reports runtime errors to the Embedded SQL for C applications. Embedded SQL for C applications.

• The application checks the error fields The application checks the error fields and status indicators of the SQLCA data and status indicators of the SQLCA data structure to determine the success or structure to determine the success or failure of an embedded SQL statement. failure of an embedded SQL statement.

Page 9: Programmatic SQL

SQLCASQLCA

/* Connect to database*/EXEC SQL CONNECT :username USING :connectString;If(sqlca.sqlcode < 0) exit(-1);

/* Display message for user and create the table */printf (“Creating VIEWING table\n”);

EXEC SQL CREATE TABLE Viewing (propertyNo VARCHAR2(5) NOT NULL, clientNo VARCHAR2(5) NOT NULL,

viewDate DATE NOT NULL, comments VARCHAR2(40));

if (sqlca.sqlcode >= 0) /* Check success */

-SQLCA.sqlcode

= 0 successfully executed

> 0 statement executed but with an exception

< 0 error occurred – statement did not execute

Page 10: Programmatic SQL

Error HandlingError Handling

• The WHENEVER statementThe WHENEVER statementEXEC SQL WHENEVER <condition> <action>EXEC SQL WHENEVER <condition> <action>

CONTINUECONTINUEDO DO name (args)name (args)

DO BREAKDO BREAKDO CONTINUEDO CONTINUEGOTO GOTO labellabel

STOPSTOP

SQLERRORSQLERROR SQLWARNINGSQLWARNING

NOT FOUNDNOT FOUND

EXEC SQL WHENEVER SQLERROR GOTO error1;

EXEC SQL WHENEVER SQLWARNING STOP;

Page 11: Programmatic SQL

The WHENEVER statementThe WHENEVER statement

EXEC SQL WHENEVER SQLERROR GOTO error1;EXEC SQL WHENEVER SQLERROR GOTO error1;EXEC SQL INSERT INTO EXEC SQL INSERT INTO Viewing Viewing VALUES VALUES (‘CR76’, ‘PA14’, (‘CR76’, ‘PA14’,

’12-MAY-2001’, ‘NOT ENOUGH SPACE’);’12-MAY-2001’, ‘NOT ENOUGH SPACE’);

EXEC SQL INSERT INTO EXEC SQL INSERT INTO Viewing Viewing VALUES VALUES (‘CR77’, ‘PA14’, (‘CR77’, ‘PA14’, ’12-MAY-2001’, ‘QUITE LIKE IT’);’12-MAY-2001’, ‘QUITE LIKE IT’);

-------------HOW PRECOMPILER READS -------------HOW PRECOMPILER READS IT------------IT------------

EXEC SQL WHENEVER SQLERROR GOTO error1;EXEC SQL WHENEVER SQLERROR GOTO error1;EXEC SQL INSERT INTO EXEC SQL INSERT INTO Viewing Viewing VALUES VALUES (‘CR76’, ‘PA14’, (‘CR76’, ‘PA14’,

’12-MAY-2001’, ‘NOT ENOUGH SPACE’);’12-MAY-2001’, ‘NOT ENOUGH SPACE’);if (sqlca.sqlcode < 0) goto error1if (sqlca.sqlcode < 0) goto error1;;

EXEC SQL INSERT INTO EXEC SQL INSERT INTO Viewing Viewing VALUES VALUES (‘CR77’, ‘PA14’, (‘CR77’, ‘PA14’, ’12-MAY-2001’, ‘QUITE LIKE IT’);’12-MAY-2001’, ‘QUITE LIKE IT’);

if (sqlca.sqlcode < 0) goto error1if (sqlca.sqlcode < 0) goto error1;;

Page 12: Programmatic SQL

Host Language VariablesHost Language Variables

- Program variable declared in the host Program variable declared in the host language.language.

- Can be used in embedded SQL Can be used in embedded SQL statementsstatements

- Can be used within the WHERE clause Can be used within the WHERE clause of SELECT statementof SELECT statement

- Cannot be used to represent database Cannot be used to represent database objects, such as table names or objects, such as table names or column names.column names.

Page 13: Programmatic SQL

Host Language VariableHost Language Variable

- Must be declared to SQL as well as being Must be declared to SQL as well as being declared in the syntax of the host language.declared in the syntax of the host language.

- All host variables must be declared to SQL All host variables must be declared to SQL in this block, which must appear before any in this block, which must appear before any of the variables are used in an embedded of the variables are used in an embedded SQL statement.SQL statement.

EXEC SQL BEGIN DECLARE SECTION;EXEC SQL BEGIN DECLARE SECTION;float increment;float increment;

EXEC SQL END DECLARE SECTION;EXEC SQL END DECLARE SECTION;

Page 14: Programmatic SQL

Host Language VariablesHost Language Variables

To use a host variable in an embedded To use a host variable in an embedded SQL statement, the variable name is SQL statement, the variable name is prefixed by a colon.prefixed by a colon.

For example,For example,

EXEC SQL UPDATE EXEC SQL UPDATE StaffStaff SET SET salary = salary salary = salary + :increment+ :increment

WHERE WHERE staffNo = ‘SL12’;staffNo = ‘SL12’;

Page 15: Programmatic SQL

Retrieving data using Retrieving data using embedded SQLembedded SQL

EXEC SQL SELECT EXEC SQL SELECT fName, lName, addressfName, lName, address

INTO INTO :firstName, :lastName, :address, :firstName, :lastName, :address,

FROM FROM PrivateOwnerPrivateOwner

WHERE WHERE ownerNo = ‘CO21’;ownerNo = ‘CO21’;

Page 16: Programmatic SQL

Difference between Static and Difference between Static and Dynamic SQLDynamic SQL

Static SQL does not allow host variables to be used in Static SQL does not allow host variables to be used in place of table names or column names.place of table names or column names.

For example,For example,

EXEC SQL BEGIN DECLARE SECTION;EXEC SQL BEGIN DECLARE SECTION;char Viewing;char Viewing;

EXEC SQL END DECLARE SECTION;EXEC SQL END DECLARE SECTION;EXEC SQL INSERT INTO EXEC SQL INSERT INTO :Viewing:Viewing

VALUES VALUES (‘CR76’, ‘PA14’, ‘5-MAY-2001’, ‘Not (‘CR76’, ‘PA14’, ‘5-MAY-2001’, ‘Not enough space’);enough space’);

Page 17: Programmatic SQL

List of embedded SQL List of embedded SQL statementsstatements

Declarative StatementDeclarative StatementEXEC SQL ARRAYLEN EXEC SQL ARRAYLEN To use host arrays To use host arrays EXEC SQL BEGIN DECLARE EXEC SQL BEGIN DECLARE SECTION SECTION EXEC SQL END DECLARE EXEC SQL END DECLARE SECTION SECTION

To declare host To declare host variables variables

EXEC SQL DECLARE EXEC SQL DECLARE To name SQL objects To name SQL objects

EXEC SQL INCLUDE EXEC SQL INCLUDE To copy in filesTo copy in files

EXEC SQL TYPE EXEC SQL TYPE To equivalence To equivalence datatypesdatatypes

EXEC SQL VAR EXEC SQL VAR To equivalence To equivalence variablesvariables

EXEC SQL WHENEVER EXEC SQL WHENEVER To handle runtime To handle runtime errorserrors

Page 18: Programmatic SQL

Executable StatementsExecutable StatementsEXEC SQL ALLOCATEEXEC SQL ALLOCATE

To define and control To define and control datadata

EXEC SQL ALTEREXEC SQL ALTER

EXEC SQL ANALYZEEXEC SQL ANALYZE

EXEC SQL COMMENTEXEC SQL COMMENT

EXEC SQL CONNECTEXEC SQL CONNECT

EXEC SQL CREATEEXEC SQL CREATE

EXEC SQL DROPEXEC SQL DROP

EXEC SQL DELETEEXEC SQL DELETE

To query and manipulate dataTo query and manipulate dataEXEC SQL FETCHEXEC SQL FETCH

EXEC SQL INSERTEXEC SQL INSERT

EXEC SQL COMMITEXEC SQL COMMIT To process transactionsTo process transactionsEXEC SQL ROLLBACKEXEC SQL ROLLBACK

Page 19: Programmatic SQL

Statements for Dynamic Statements for Dynamic SQLSQL

EXEC SQL DESCRIBEEXEC SQL DESCRIBE

To use dynamic SQLTo use dynamic SQLEXEC SQL EXECUTEEXEC SQL EXECUTE

EXEC SQL PREPAREEXEC SQL PREPARE

Page 20: Programmatic SQL

Running SQL CommandsRunning SQL Commands

Any SQL command can be run from within an embedded SQL Any SQL command can be run from within an embedded SQL application. Below are some examples of how to do that. application. Below are some examples of how to do that.

Creating a tableCreating a table: :

- EXEC SQL CREATE TABLE foo (number integer, ascii char(16));- EXEC SQL CREATE TABLE foo (number integer, ascii char(16));

- EXEC SQL CREATE UNIQUE INDEX num1 ON foo(number);- EXEC SQL CREATE UNIQUE INDEX num1 ON foo(number);

- EXEC SQL COMMIT; - EXEC SQL COMMIT;

Inserting rowsInserting rows: :

- EXEC SQL INSERT INTO foo (number, ascii) VALUES (9999, - EXEC SQL INSERT INTO foo (number, ascii) VALUES (9999,

'doodad');'doodad');

Page 21: Programmatic SQL

Running SQL CommandsRunning SQL Commands

Deleting rowsDeleting rows: :

- EXEC SQL DELETE FROM foo WHERE number = - EXEC SQL DELETE FROM foo WHERE number = 9999; 9999;

Single-row SelectSingle-row Select::

- EXEC SQL SELECT foo INTO :FooBar FROM table1 - EXEC SQL SELECT foo INTO :FooBar FROM table1 WHERE ascii = ‘doodad’;WHERE ascii = ‘doodad’;

Page 22: Programmatic SQL

Running SQL CommandsRunning SQL Commands

Selecting using CursorsSelecting using Cursors::- EXEC SQL DECLARE foo_bar CURSOR FOR- EXEC SQL DECLARE foo_bar CURSOR FOR

SELECT number, ascii FROM fooSELECT number, ascii FROM fooORDER BY ascii;ORDER BY ascii;

- EXEC SQL OPEN foo bar;- EXEC SQL OPEN foo bar;- EXEC SQL FETCH foo_bar INTO :FooBar, DooDad;- EXEC SQL FETCH foo_bar INTO :FooBar, DooDad;……- EXEC SQL CLOSE foo_bar;- EXEC SQL CLOSE foo_bar;

UpdatesUpdates::- EXEC SQL UPDATE foo SET ascii = ‘foobar’ WHERE - EXEC SQL UPDATE foo SET ascii = ‘foobar’ WHERE number = 9999;number = 9999;

Page 23: Programmatic SQL

BibliographyBibliography

- Connolly, Thomas, Carolyn Begg. “Database Connolly, Thomas, Carolyn Begg. “Database Systems: A practical approach to design, implementation, Systems: A practical approach to design, implementation, and management”. 3and management”. 3rdrd ed. 2002. ed. 2002.

- http://msdn.microsoft.com/library/default.asp?url=/library/ehttp://msdn.microsoft.com/library/default.asp?url=/library/enus/esqlforc/ec_6_epr_01_3m03.aspnus/esqlforc/ec_6_epr_01_3m03.asp

- http://www-db.stanford.edu/~ullman/fcdb/oracle/or-proc.hthttp://www-db.stanford.edu/~ullman/fcdb/oracle/or-proc.html#sqlml#sql