0% found this document useful (0 votes)
5 views12 pages

Dbms

The document discusses SQL programming techniques, focusing on embedded SQL, dynamic SQL, and database stored procedures. It outlines various approaches to database programming, including embedding SQL commands in general-purpose programming languages, using libraries of database functions, and designing new programming languages. Additionally, it addresses issues like impedance mismatch between database and programming language models, and provides examples of using embedded SQL for database interactions.

Uploaded by

Surya kanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Dbms

The document discusses SQL programming techniques, focusing on embedded SQL, dynamic SQL, and database stored procedures. It outlines various approaches to database programming, including embedding SQL commands in general-purpose programming languages, using libraries of database functions, and designing new programming languages. Additionally, it addresses issues like impedance mismatch between database and programming language models, and provides examples of using embedded SQL for database interactions.

Uploaded by

Surya kanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

dbms

Chapter4 (part-2): SQL-The relational database


Standard
• Embedded SQL

• Dynamic SQL

• Database stored procedures and SQL/PSM

Introduction to SQL Programming Techniques

• Most database access is through software programs that implement database applications.

• The software is generally developed in a general-purpose programming language such as


java, COBOL, C/C++ etc.

• Host Language: general-purpose programming language

• Data sub-language: SQL

• Database programming language: Special language developed for writing database


applications.

Database Programming: Issues and Techniques

• Most database systems have an interactive interface where these SQL commands can be
typed directly giving input to database.

• The interactive interface is convenient for ad-hoc queries.

• But in practice, database interactions are executed through programs that are carefully
designed and tested.

• These application programs or database applications are used as canned transactions by the
end users.

• A database can be accessed through an application program that implements a Web


Interface.

Approaches to Database Programming

• Several techniques exist for including database interactions in application programs:

1. Embedding database commands in a general-purpose programming language

2. Using a library of database functions

3. Designing a brand new language

• First two approaches are common but it suffers from the problem of impedance mismatch.

• Third approach is more appropriate for applications that have intensive database
interactions.

Embedded SQL

Embedding database commands in a general-purpose

1
dbms

programming language:

• Database statements are embedded into the host programming language, they are identified
by a special prefix.

• For example, the prefix for embedded SQL is the string EXEC SQL, which precedes all SQL
commands in a host language program.

• A precompiler or preprocessor scans the source program code to identify database


statements and extract them for processing by the DBMS

• They are replaced in the program by function call to the DBMS-generated code.

A library of database functions

Using a library of database functions

• These functions are made available to the host programming language for the database calls.

• For example, there could be functions to connect to a database, execute a query, execute an
update etc.

• The actual database query, and update commands and any other necessary information are
included as parameters in the function calls.

• This approach provides Application programming interface (API) for accessing a database
from application programs.

A brand new language

Designing a brand new language

• A database programming language is designed from scratch to be compatible with the


database model and query language.

• Additional programming structures such as loops and conditional statements are added to
the database language to convert it into a full-fledged programming language

Impedance Mismatch

• A problem occurs because of difference between the database model and the programming
language model.

• For example the practical relational model has three main constructs: attributes and their
data types, tuples and tables.

• The first problem that may occur is that the data type of the programming language differ
from attribute data types in the data model.

• Hence it is necessary to have a binding for each host programming language that specifies
for each attribute type and the compatible programming language types.

• Data types in C++ and java differ from the SQL data types

• Another problem occurs because the results of most queries are sets or multisets of tuples,
and each tuple is formed of sequence of attribute values.

2
dbms

• In the program it is often necessary to access individual data values within individual tuples
for printing or processing.

• Hence a binding is needed to map the query result data structure, which is a table, to an
appropriate data structure in the programming language.

• A mechanism is needed to loop over the tuples in a query result in order to access a single
tuple at a time and extract individual values from the tuple.

• The extracted attribute values are typically copied to appropriate program variables for
further processing by the program.

• A cursor or iterator variable is used to loop over the tuples in a query result.

• Individual values within each tuple are typically extracted into distinct program variables of
the appropriate type.

• Impedance mismatch is less of problem when a special database programming language is


designed that uses the same data model and data types as the database model.

• One example of such a language is Oracle’s PL/SQL.

• For object databases, the object data model is quite similar to the data model of the Java
programming language,

• Thus impedance mismatch is greatly reduced when Java is used as host language for
accessing a Java-compatible object database.

Typical sequence of interaction in Database programming

• Generally, architecture for database access is the client-server model

• A client program handles the logic of a software application but includes some calls to one or
more database servers to access or update the data.

• Writing such an application, a common sequence of interaction is followed.

Step 1:

• When the client program requires access to a particular database, the program must first
establish or open a connection to the database server.

• Typically, this involves specifying the Internet address (URL) of the machine where the
database server is located, plus providing a login account name and password for database
access.

Step 2:

• Once the connection is established, the program can interact with the database by
submitting queries, updates and other database commands.

• In general most types of SQL statements can be included in an application program.

Step 3:

• When the program no longer needs access to a particular database, should terminate or
close the connection to the database.

3
dbms

• A program can access multiple databases if needed.

• In some database programming approaches, only one connection can be active at a time,
whereas in other approaches multiple connections can be established simultaneously.

Embedded SQL

• SQL statements can be embedded in a general purpose programming language (host


language) such as C, ADA, COBOL, or PASCAL.

• Most SQL statements- including data or constraint definitions, queries, updates or view
definitions-can be embedded in the host language program.

• Embedded SQL statement is distinguished from programming language by prefixing it with


the keywords EXEC SQL so that preprocessor can separate embedded SQL statements from
the host language code.

• The SQL statements can be terminated by a semicolon(;) or a matching END-EXEC.

Using C as the host programming language

• Within an embedded SQL command, specially declared C program variables can be referred.

• These variables are called shared variables because these are used by both C and embedded
SQL.

• Shared variables are prefixed by a colon(:) when they appear in an SQL Statement.

• This distinguishes program variables names from the names of database schema constructs
such as attributes and relations

• It allows program variables to have the same names as attribute names.

• A few of the common bindings of C types to SQL types are as follows:

• The SQL types INTEGER, SMALLINT, REAL, and DOUBLE are mapped to the C types long,
short, float, and double respectively.

• Fixed-length and varying-length strings (CHAR [i], VARCHAR [i]) in SQL can be mapped to
array of characters (char [i+1], varchar [i+1]) in C that are one character longer than the SQL
type because strings in C are terminated by a NULL character (\0),which is not part of
character it self.

C program segment declaring variables

1. int loop;

2. EXEC SQL BEGIN DECLARE SECTION;

3. varchar fname [16], lname [16], address [31];

4. char ssn [11], bdate [10], minit [2];

5. float salary, raise;

6. int SQLCODE; char SQLSTATE [6];

7. EXEC SQL END DECLARE SECTION;

4
dbms

8. The variables SQLCODE and SQLSTATE are used to communicate errors and exception
conditions between the database system and the program.

9. Connecting to the Database

10. The SQL command for establishing a connection to a database has the following form:

11. CONNECT TO<server name>AS<connection name>

12. AUTHORIZATION<user account name and password>;

13. In general, since a user or program can access several database servers, several connections
can be established, but only one connection can be active at any point in time.

14. The programmer or user can use the <connection name> to change from the currently active
connection to a different one by using the following command:

15. SET CONNECTION <connection name>;

16. Once a connection is no longer needed, it can be terminated by the following command:

17. DISCONNECT<connection name>;

18. Communicating between the program and the DBMS

19. Using SQLCODE and SQLSTATE:

20. The two special communication variables that are used by the DBMS to communicate
exception or error conditions to the program are SQLCODE and SQLSTATE.

21. The SQLCODE variable shown in the example is an integer variable.

22. After each database command is executed, the DBMS returns a value in SQLCODE.

23. A value of 0 indicates that the statement was executed successfully by the DBMS.

24. If SQLCODE>0 (or, more specifically, if SQLCODE=100), this indicates that no more data are
available in a query result.

25. If SQL<0,this indicates some error has occurred.

26. In some systems-for example, in the Oracle RDBMS-SQLCODE is field in record structure
called SQLCA (SQL communication area), so it is referenced as SQLCA.SQLCODE.

27. In this case, the definition of SQLCA must be included in the C program by including the
following line:

28. EXEC SQL include SQLCA;

29. In the later versions of the SQL standard, a communication variable called SQLSTATE was
added, which is a string of five characters.

30. A value of ‘00000’ in SQLSTATE indicates no error or exception; other variables indicates
various errors or exceptions.

31. For example, ‘02000’ indicates ‘no more data’ when using SQLSTATE.

32. Currently, both SQLSTATE and SQLCODE are available in the SQL standard.

5
dbms

33. In the later versions of the SQL standard, a communication variable called SQLSTATE was
added, which is a string of five characters.

34. A value of ‘00000’ in SQLSTATE indicates no error or exception; other variables indicates
various errors or exceptions.

35. For example, ‘02000’ indicates ‘no more data’ when using SQLSTATE.

36. Currently, both SQLSTATE and SQLCODE are available in the SQL standard.

37. In the later versions of the SQL standard, a communication variable called SQLSTATE was
added, which is a string of five characters.

38. A value of ‘00000’ in SQLSTATE indicates no error or exception; other variables indicates
various errors or exceptions.

39. For example, ‘02000’ indicates ‘no more data’ when using SQLSTATE.

40. Currently, both SQLSTATE and SQLCODE are available in the SQL standard.

41. Many of the error and exception codes returned in SQLSTATE are supposed to be
standardized for all SQL vendors and platforms, where the codes returned in SQLCODE are
not standardized but are defined by the DBMS vendor.

42. Hence is better to use SQLSTATE because this makes error handling in the application
programs independent of a particular DBMS.

Example of Embedded SQL

Retrieving single tuple with Embedded SQL:

• Program segment reads a ssn of an employee and prints some information from
corresponding EMPLOYEE record in the database.

• INTO clause specifies the program variables into which attribute values from the database
are retrieved.

• SQLCODE is used for communication between database and program.

• If SQLCODE returns 0, the statement is executed without errors or exception

C program segment declaring variables

1. loop =1;

2. while (loop) {

3. prompt (“Enter a Social Security Number:”, ssn);

4. EXEC SQL

5. select Fname, Minit, Lname, Address, Salary

6. into :fname, :minit, :lname, :address, :salary

7. from EMPLOYEE where Ssn = :ssn;

6
dbms

8. if (SQLCODE ==0) printf (fname, minit, lname, address,


salary)

9. else printf (“Social Security Number does not exist);

10. prompt (“More Social Security Number (enter 1 for


yes, 0 for no):”, loop);

Retrieving multiple tuple with Embedded SQL using

cursors:

• Cursor is declared when SQL command is declared in program

• An OPEN CURSOR command fetches the query result from the database and sets the cursor
to a position before the first row in the result of the query.

• FETCH command moves the cursor to the next row in the result of the query, and copying its
attribute values into C variables

• CLOSE CURSOR is issued to end the processing.

• The cursor variable is basically an iterator that iterates over the tuples in the query result one
tuple at a time.

• To determine when all the tuples in the result of the query have been processed, the
communication variable SQLCODE is checked.

• If a FETCH command is issued that result in moving the cursor till the last tuple in the result
of the query, a positive value is returned in SQLCODE, indicating that no data was found.

• The programmer uses positive value of SQLCODE to terminate a loop over the tuple in the
query result.

• In general, numerous cursors can be opened at the same time.

• When a cursor is defined for rows that are to be modified, we must add the clause FOR
UPDATE OF in the cursor declaration and list the names of any attributes that will be updated
by the program.

• If rows are to be deleted, the keywords FOR DELETE must be added without specifying any
attributes.

• If the result of the query is to be used for retrieval purposes only, there is no need to include
the FOR UPDATE OF

• In the embedded UPDATE command, the condition WHERE CURRENT OF <cursor_name>


specifies that the current tuple, referenced by the cursor is the one to be updated.

• Prompt (“Enter the Department Name:”, dname);

• EXEC SQL

• select Dnumber into :dnumber

• from DEPARTMENT where Dname = :dname;

• EXEC SQL DECLARE EMP CURSOR FOR

7
dbms

• select Ssn, Fname, Minit, Lname, Salary

• from EMPLOYEE where Dno = :dnumber

• FOR UPDATE OF Salary;

• EXEC SQL OPEN EMP

• EXEC SQL FETCH from EMP into :ssn, :fname, :minit, :lname, :salary;

• while (SQLCODE == 0) {

• printf (“Employee Name is:”, Fname, Minit, Lname);

• prompt (“Enter the raise amount:”, raise);

• EXEC SQL

• update EMPLOYEE

• set Salary = Salary +:raise

• where CURRENT OF EMP;

• EXEC SQL FETCH from EMP into :ssn, :fname, :minit, :lname, :salary;

• }

• EXEC SQL CLOSE EMP;

The general form of a cursor declaration is as follows:

• DECLARE <cursor_name> [ INSENSITIVE] [SCROLL] CURSOR

[WITH HOLD ] FOR <query specification>

[ORDER BY <ordering specification>]

[FOR READ ONLY | FOR UPDATE [OF <attribute list>]];

• The default is that the query is for retrieval purposes (FOR READ ONLY)

• When the optional keyword SCROLL is specified in a cursor declaration, it is possible to


position the cursor in other ways than for purely sequential access.

• A fetch orientation can be added to the FETCH command, whose value can be one of NEXT,
PRIOR, FIRST, LAST, ABOSULTE i, and RELATIVE i.

• i must evaluate to an integer value that specifies an absolute tuple position or a tuple
position relative to the current cursor position respectively.

• The default fetch orientation is NEXT.

• The fetch orientation allows the programmer to move the cursor around the tuple in the
query result with greater flexibility, providing random access by position or access in reverse
order.

• When SCROLL is specified on the cursor, the general form a FETCH command is as follows,
with the parts in square brackets being optional:

8
dbms

FETCH [[<fetch orientation>] FROM] <cursor name> INTO <fetch target list>;

• The ORDER BY clause orders the tuples so that the FETCH command will fetch them in the
specified order.

Dynamic SQL

Specifying Queries at Runtime Using Dynamic SQL:

• The embedded SQL queries are written as part of the host program source code.

• Hence, any time we want to write to a different query, we must write a new program, and go
through all the steps involved (compiling, debugging, testing, and so on).

• Sometimes, it is convenient to write a program that can execute different SQL queries or
updates dynamically or runtime.

• For example, we may want to write a program that accepts an SQL query typed from the
monitor, executes it, and displays its result, such as the interactive interfaces available for
most relational DBMSs.

• Another example is when a user friendly interface generates SQL queries dynamically for the
user based on point and click operation on a graphical schema.

• A string is input by the user into the string variable sqlupdatestring.

• String should be a SQL Command.

• String is then prepared as an SQL command by associating it with the SQL variable
sqlcommand.

• SQL command executes.

• In this case no syntax check or other types of checks on the command are possible, whereas
in embedded SQL the query could be checked at compile time because its text was in the
program source code.

• A dynamic query is much more complicated.

• Because we do not know the type or the number of attributes to be retrieved by the SQL
query when we are writing the program.

• A complex data structure is sometimes needed to allow for different number and the
dynamic query.

Dynamic SQL (Example)

1. EXEC SQL BEGIN DECLARE SECTION;

2. varchar sqlupdatestring [256];

3. EXEC SQL END DECLARE SECTION;

…….

4. prompt (“Enter the Update Command:”, sqlupdatestring);

5. EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring;

9
dbms

6. EXEC SQL EXECUTE sqlcommand;

7. The reason for separating PREPARE and EXECUTES is that if the command is to be executed
multiple times in a program, it can be prepared only once.

8. Preparing the command generally invokes syntax and other types of checks by the systems as
well as generating the code for executing it.

Database stored procedures and SQL/PSM

• Stored procedures are program modules that are stored by the DBMS at the database server.

• The extensions to SQL are specified in the standard to include general-purpose programming
constructs in SQL.

• These extensions are known as SQL/PSM (Persistent Stored Modules) and can be used to
write stored procedures.

• SQL/PSM also serves as a programming language SQL with some programming constructs,
such as conditional statements and loops.

Database stored procedures and Functions

• In embedded and dynamic SQL, there was an implicit assumption that the database
application program was running on a client machine that is different from the machine on
which database server is located.

• Database stored procedures are stored and executed by the DBMS at the database server.

• These are historically known as database stored procedures, also they can be functions or
procedures.

• The term used in the SQL standard for the stored procedures is persistent stored modules
because these programs are stored persistently by the DBMS

Stored procedures are useful in the following

circumstances:

1. If a database program is needed by several applications, it can be stored at the server and
invoked by any of the application programs.

• This reduces duplication of effort and improves software modularity.

2. Executing a program at the server can reduce data transfer and communication cost between
the client and server in certain situations.

3. These procedures can enhance the modeling power provided by views by allowing more
complex types of derived data to be made available to the database users.

4. Additionally they can be used to check for complex constraints that are beyond the
specification power of assertions and triggers.

5. The general form of declaring stored procedures is as follows:

CREATE PROCEDURE <procedure name>(<parameters>)

10
dbms

<local declarations>

<procedure body>;

6. These parameters and local declarations are optional, and are specified only if needed.

7. For declaring a function, a return type is necessary, so the declaration form is

CREATE FUNCTION <function name>(<parameters>)

RETURNS<return type>

<local declarations>

<function body>;

• Each parameter should have a parameter type that is one of the SQL data types.

• Each parameter should also have a parameter mode, which is one of IN, OUT, or INOUT.

• These correspond to parameters whose values are input only, output only and both input
and output respectively.

• The procedures and functions are stored persistently by the DBMSs, it should be possible to
call them from the various SQL interfaces and programming techniques.

• The CALL statement in the SQL standard can be used to invoke a stored procedure-either
from an interactive interface or from embedded SQL or SQLJ.

• The format of the statement is as follows:

CALL<procedure or function name>(<argument list>);

SQL/PSM: Extending SQL for specifying persistent stored modules

• SQL/PSM is the part of the SQL standard that specifies how to write persistent stored
modules.

• It includes the statements to create functions and procedures.

• It also includes additional programming constructs to enhance the power of SQL for the
purpose of writing the body of the procedure.

• SQL/PSM provide constructs for conditional statements and for looping statements.

• The conditional branching statement in SQL/PSM has the following form:

IF<condition>THEN <statement list>

ELSEIF<condition>THEN <statement list>

……

ELSEIF <condition>THEN <statement list>

ELSE<statement list>

11
dbms

END IF;

SQL/PSM: Extending SQL for specifying persistent stored modules

1. CREATE FUNCTION Dept_size (IN deptno INTEGER)

2. RETURNS VARCHAR [17]

3. DECLARE No_of_emps INTEGER;

4. SELECT COUNT(*) INTO No_of_emps

5. FROM EMPLOYEE WHERE Dno = deptno;

6. If No_of_emps > 100 THEN RETURN “HUGE”

7. ELSEIF No_of_emps >25 THEN RETURN “LARGE”

8. ELSEIF No_of_emps >10 THEN RETURN “MEDIUM”

9. ELSE RETURN “SMALL”

10. ENDIF

12

You might also like