Week-6-Accessing Databases
Week-6-Accessing Databases
Advanced
Objective
▪ The objective of Unit 3 is to understand the accessing of database
from various applications.
▪ This unit explains the fundamentals of embedding SQL queries in high
level languages.
▪ Implementation of cursors in PL/SQL
Accessing Databases from Applications
▪ Embedded SQL
▪ The SQL commands embedded in any programming language is called as Embedded SQL.
▪ The language which the SQL is embedded is called as host language. The languages
such as C, C++, Java, Python.
▪ The SQL statements are embedded with the host language whenever required.
▪ The compiler of the host language is invoked for SQL pre-processing.
▪ The special variable called host variable is used in the code to alternate between
application and database.
▪ The variables of host language must be declared in SQL.
▪ The host variables are classified into two types
o Input Host variables (move data to database system)
o Output Host variables (acquire data from database system
Declaring Variables and Exceptions
▪ The variables defined in the host program are referred by SQL
statements with the prefixed colon (:)
▪ SYNTAX
EXEC SQL BEGIN DECLARE
SECTION
... EXEC SQL END DECLARE SECTION
OPEN s1
Cursor
Fetch Data from the Cursor There is a total of 6 methods to access data from the
cursor. They are as follows:
1.FIRST is used to fetch only the first row from the cursor table.
2.LAST is used to fetch only the last row from the cursor table.
3.NEXT is used to fetch data in a forward direction from the cursor table.
4.PRIOR is used to fetch data in a backward direction from the cursor table.
5.ABSOLUTE n is used to fetch the exact nth row from the cursor table.
6.RELATIVE n is used to fetch the data in an incremental way as well as a decremental
way.
Syntax:
FETCH NEXT/FIRST/LAST/PRIOR/ABSOLUTE n/RELATIVE n FROM
cursor_name
Cursors
▪ Cursors are defined as pointers to access each record in the database.
▪ This method is used to overcome the problem of mismatch between
programming languages and SQL.
▪ Cursor can be declared on any existing database relation.
▪ There are two types
▪ Read-only and Forward-only
▪ The read only cursors will not update the data.
▪ Forward only cursors can be moved from first row to the last row.
▪ a)Steps for using cursors
(i)Declare the cursor for the SQL statement
(ii)Open the cursor
(iii)Fetch the rows
(iv)Close the cursor
Basic Cursor Definition and Usage
▪ Cursors are used to fetch single rows from the table.
▪ Open cursor is used with select statement
▪ Cursor cannot be used with insert, delete and update statement.