Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 55

Chapter 3

Database Programing

1
Chapter Outline
I. Introduction Database Programming
II. Database Programming Approaches
III.Typical steps in Database Programming
IV. Embedded SQL
V. Database programming language
VI. Database Programming with Function
Calls
VII.Summary

2
I. Database Programming
• Objective:
– To access a database from an application program
(as opposed to interactive interfaces)
• Why?
– An interactive interface is convenient but not
sufficient
• A majority of database operations are made thru
application programs (increasingly thru web
applications)

3
I. Database Programming (contd.)
• Most database access in practical applications is
accomplished through software programs that
implement database applications.
• This software is usually developed in a general-
purpose programming language such as Java, C/C+
+/C#, COBOL, or some other programming
language.
• many scripting languages, such as PHP and
JavaScript, are also being used for programming of
database access within Web applications.
• It is important to note that database programming
is a very broad topic. 4
II. Database Programming Approaches
(contd.)
Several techniques exist for including database interactions in
application programs. The main approaches for database
programming are the following:
1. Embedded commands:
- Database commands are embedded in a general-purpose
programming language (host language). 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 preproccessor 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 calls to
the DBMS-generated code. This technique is generally referred to
as embedded SQL.
5
II. Database Programming Approaches
(contd.)
2. Using a library of database functions:
- A library of functions is made available to the host
programming language for database calls. For example,
there could be functions to connect to a database, execute
a query, execute an update, and so on. The actual
database query and update commands and any other
necessary information are included as parameters in the
function calls.
- This approach provides what is known as an application
programming interface (API) for accessing a database
from application programs.

6
II. Database Programming Approaches
(contd.)
3. A brand new, full-fledged language:
A database programming language is designed 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. An example of this
approach is Oracle’s PL/SQL.

7
II. Database Programming Approaches
(contd.)
- In practice, the first two approaches are more
common, since many applications are already
written in general-purpose programming languages
but require some database access. The third
approach is more appropriate for applications that
have intensive database interaction.
- One of the main problems with the first two
approaches is impedance mismatch, which does not
occur in the third approach.

8
Impedance Mismatch
• Impedance mismatch is the term used to refer to the
problems that occur because of differences between
the database model and the programming language
model.
– type mismatch and incompatibilities, e.g., the data
types available in C/C++ and Java are different, and
both differ from the SQL data types, which are the
standard data types for relational databases. Hence,
it is necessary to have a binding for each host
programming language
– set vs. record-at-a-time processing
• need special iterators to loop over query results and
manipulate individual values
9
III. Typical steps in Database Programming
When a programmer or software engineer writes a program
that requires access to a database, it is quite common for the
program to be running on one computer system while the
database is installed on another. A common architecture for
database access is the client/server model, where 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. When writing such a program, a common
sequence of interaction is the following:
1.Client program opens a connection to the database server
2.Client program submits queries to and/or updates the
database
3.When database access is no longer needed, client program
closes (terminates) the connection
10
IV. Embedded SQL
• We give an overview of the technique for how SQL
statements can be embedded in a general-purpose
programming language. The examples used with the C
language, known as embedded SQL

11
IV. Embedded SQL (contd.)
SQL Commands for Connecting to a
Database
• Connection (multiple connections are possible
but only one is active)
CONNECT TO server-name AS connection-name
AUTHORIZATION user-account-info;
• Change from an active connection to another
one
SET CONNECTION connection-name;
• Disconnection
DISCONNECT connection-name;
In following examples, we assume that the appropriate
connection has already been established to the
database, and that it is the currently active connection.
12
IV. Embedded SQL (contd.)
• Most SQL statements can be embedded in a general-
purpose host programming language such as COBOL, C,
Java

• Declaring Variables:
SQL statements can refer to Shared variables defined in
the host program. Such host-language variables must be
prefixed by a colon (:) in SQL statements and must be
declared between the commands EXEC SQL BEGIN
DECLARE SECTION and EXEC SQL END DECLARE SECTION.

13
IV. Embedded SQL (contd.)
Embedded SQL Statements
• An embedded SQL statement is distinguished
from the host language statements by
enclosing it between
EXEC SQL … END-EXEC (or semicolon)
EXEC SQL BEGIN … EXEC SQL END (or
semicolon)
– Syntax may vary with language

14
Example: Variable Declaration in Language C
0/ int loop; // will not be used in any
//embedded SQL statement
1/ EXEC SQL BEGIN DECLARE SECTION;
2/ char c_sname[20];
3/ long c_sid; Shared variables can be
4/ short c_rating; used in any embedded
SQL statement
5/ float c_age;
6/ long SQLCODE;
7/ char SQLSTATE[6] ;
8/ EXEC SQL END DECLARE SECTION;
...
Exec SQL INSERT INTO Sailors
VALUES(:c_sname, :c_sid, :c_rating, :c_age);
15
IV. Embedded SQL (contd.)
Retrieving Single Tuples with Embedded SQL
loop = 1;
while (loop) {
prompt (“Enter SSN: “, ssn);
EXEC SQL
select FNAME, LNAME, ADDRESS, SALARY
into :fname, :lname, :address, :salary
from EMPLOYEE where SSN == :ssn;
if (SQLCODE == 0) printf(fname, …);
else printf(“SSN does not exist: “, ssn);
prompt(“More SSN? (1=yes, 0=no): “, loop);
END-EXEC
}

Note: The INTO clause can be used in this way only


when the query result is a single record;if multiple16
records are retrieved, an error will be generated
IV. Embedded SQL (contd.)
A few of the common bindings of C types to SQL types
• 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 arrays 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
the character string itself.
• Although varchar is not a standard C data type, it is
permitted when C is used for SQL database programming.

17
IV. Embedded SQL (contd.)
• Exceptions
- The standard SQL-92 recognizes two special variables for
reporting errors, SQLCODE and SQLSTATE.
- SQLCODE is the older of the two and is defined to return
some negative value when an error condition arises, without
specifying further just what error a particular negative integer
denotes. C type for SQLCODE is long.
- In the Oracle RDBMS, SQLCODE is a field in a record
structure called SQLCA (SQL communication area), so it is
referenced as SQLCA.SQLCODE. In this case, the definition
of SQLCA must be included in the C program by including
the following line: EXEC SQL include SQLCA ;
- SQLSTATE associates predefined values with several
common error condition. C type for SQLSTATE is
char[6]
- One of these two variables must be declared. 18
IV. Embedded SQL (contd.)
Note: communication variables:
SQLCODE == 0: the statement was executed successfully
SQLCODE > 0: no more data (records) are available in a
query result
SQLCODE < 0: some error has occurred

SQLSTATE: a string of five characters


SQLSTATE ==‘00000’: no error or exception
other values indicate various errors or exceptions. For
Example, SQLSTATE ==‘02000’indicates ‘no more data’

it is generally better to use SQLSTATE because this


makes error handling in the application programs
independent of a particular DBMS.

19
IV. Embedded SQL (contd.)
Retrieving Multiple Tuples with Embedded SQL Using Cursors
In general, an SQL query can retrieve many tuples. In that
case, the C program will typically go through the retrieved
tuples and process them one at a time. The concept of a
cursor is used.
•A cursor (iterator) is needed to process multiple tuples
•OPEN <cursor name> command executes the query and
fetches its result.
•FETCH command move the cursor to the next tuple
•CLOSE CURSOR indicates that the processing of query
results has been completed

20
IV. Embedded SQL (contd.)
Embedded SQL in C Programming Examples
0) prompt("Enter the Department Name: ", dname) ;
1) EXEC SQL
2) select Dnumber into :dnumber
3) from DEPARTMENT where Dname = :dname ;
4) EXEC SQL DECLARE EMP CURSOR FOR
5) select Ssn, Fname, Minit, Lname, Salary
6) from EMPLOYEE where Dno = :dnumber
7) FOR UPDATE OF Salary ; //Salary will be update
8) EXEC SQL OPEN EMP ;

21
9) EXEC SQL FETCH from EMP into :ssn, :fname, :minit,
:lname, :salary ;
10) while (SQLCODE == 0) {
11) printf("Employee name is:", Fname, Minit, Lname) ;
12) prompt("Enter the raise amount: ", raise) ;
13) EXEC SQL
14) update EMPLOYEE
15) set Salary = Salary + :raise
16) where CURRENT OF EMP ;
17) EXEC SQL FETCH from EMP into :ssn, :fname, :minit,
:lname, :salary ;
18) }
19) EXEC SQL CLOSE EMP ;
Assigment: General Options for a Cursor Declaration, Fetch
command? 22
• When a cursor is defined for rows that are to be modified
(updated), 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 UPDATE must be
added without specifying any attributes.
• In the embedded UPDATE (or DELETE) command, the condition
WHERE CURRENT OF<cursor name> specifies that the current
tuple referenced by the cursor is the one to be updated (or
deleted),
• Notice that declaring a cursor and associating it with a query does
not execute the query; the query is executed only when the OPEN
<cursor name> command (line 8) is executed.
• Also notice that there is no need to include the FOR UPDATE OF
clause if the results of the query are to be used for retrieval
purposes only (no update or delete).
23
Dynamic SQL: Composing and executing new (not
previously compiled) SQL statements at run-time.
In some cases, it is convenient to write a program
that can execute different SQL queries or updates
(or other operations) dynamically at runtime:
• A program accepts SQL statements from the
keyboard at run-time
• Point-and-click operations on a graphical
interface translates to certain SQL query
•Dynamic update is relatively simple
•Dynamic query can be complex because the type
and number of retrieved attributes are unknown at
compile time
24
Dynamic SQL: An Example
EXEC SQL BEGIN DECLARE SECTION;
varchar sqlupdatestring[256];
EXEC SQL END DECLARE SECTION;

prompt (“Enter update command:“, sqlupdatestring);
EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring;
EXEC SQL EXECUTE sqlcommand;

 The reason for separating PREPARE and EXECUTE is


that if the command is to be executed multiple
times in a program, it can be prepared only once.
Preparing the command generally involves syntax
and other types of checks by the system as well as
generating the code for executing it.

25
V. Database programming language
Database Stored Procedures
• Persistent procedures/functions (modules) are stored
locally and executed by the database server
– As opposed to execution by clients
• Advantages:
– If the procedure is needed by many applications, it
can be invoked by any of them.
– Execution by the server reduces communication costs
– Enhance the modeling power of views
• Disadvantages:
– Every DBMS has its own syntax and this can make the
system less portable 26
V. Database programming language (contd.)
Stored Procedure Constructs
• A stored procedure
CREATE PROCEDURE procedure-name (params)
local-declarations
procedure-body;
• A stored function
CREATE FUNCTION fun-name(params) RETURNS return-type
local-declarations
function-body;
• Calling a procedure or function
CALL procedure-name/function-name (arguments);

27
V. Database programming language (contd.)

Stored Procedure Constructs


• Declarations of local variables
DECLARE <name> <type> ;
• Assignment Statements
SET <variable> = <expression>;
• Statement groups
We can form a list of statements ended by semicolons
and surrounded by keywords BEGIN and END. This
construct is treated as a single statement and can
appear anywhere a single statement can.

28
V. Database programming language (contd.)
SQL Persistent Stored Modules (SQL/PSM)
• SQL/PSM:
– is part of the latest revision to the SQL standard
for writing persistent stored modules. Each
commercial DBMS offers its own extension of
PSM.
• SQL + stored procedures/functions +
additional programming constructs
– E.g., branching and looping statements
– Enhance the power of SQL
29
V. Database programming language (contd.)

SQL Persistent Stored Modules (SQL/PSM)

• 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>
END IF ;
30
V. Database programming language (contd.)
SQL Persistent Stored Modules (SQL/PSM)
• WHILE <condition> DO
<statement list>
END WHILE ;
• REPEAT
<statement list>
UNTIL <condition>
END REPEAT ;

31
Example 1.
create procedure sp_InsertOrderAndOrderDetail
@customerid int,
@orderdate datetime,
@orderid int,
@itemid int,
@quantity decimal ,
as
begin
insert into orders
values(@customerid, @orderdate)
insert into orderdetail
values(@orderid, @itemid, @quantity)
End.

32
Example 2.
USE AdventureWorks2012;
GO
CREATE PROCEDURE uspGetEmployeesTest2
@LastName nvarchar(50),
@FirstName nvarchar(50)
AS
SELECT FirstName, LastName, Department
FROM vEmployeeDepartmentHistory
WHERE FirstName = @FirstName AND LastName = @LastName
AND EndDate IS NULL;
GO

33
Example 2 (contd.)
To run the procedure:
EXECUTE HumanResources.uspGetEmployeesTest2
N'Ackerman', N'Pilar';
-- Or
EXEC HumanResources.uspGetEmployeesTest2 @LastName
= N'Ackerman', @FirstName = N'Pilar';
GO
-- Or
EXECUTE HumanResources.uspGetEmployeesTest2
@FirstName = N'Pilar', @LastName = N'Ackerman';
GO 34
Example 3.
CREATE FUNCTION dbo.ufnGetInventoryStock(@ProductID int)
RETURNS int
AS -- Returns the stock level for the product.
BEGIN
DECLARE @ret int;
SELECT @ret = SUM(p.Quantity)
FROM Production.ProductInventory p
WHERE p.ProductID = @ProductID AND p.LocationID = '6';
IF (@ret IS NULL)
SET @ret = 0;
RETURN @ret;
END;
GO
35
Example 3 (contd).
To run the function:
SELECT ProductModelID, Name,
dbo.ufnGetInventoryStock(ProductID) AS
CurrentSupply
FROM Production.Product
WHERE ProductModelID BETWEEN 75 and 80;

36
Example 4.
The following example creates an inline table-valued function in
the AdventureWorks2012 database. The function takes one
input parameter, a customer (store) ID, and returns the columns
ProductID, Name, and the aggregate of year-to-date sales
as YTD Total for each product sold to the store
CREATE FUNCTION Sales.ufn_SalesByStore (@storeid int)
RETURNS TABLE AS
RETURN (
SELECT P.ProductID, P.Name, SUM(SD.LineTotal) AS 'Total'
FROM Production.Product AS P
JOIN Sales.SalesOrderDetail AS SD ON SD.ProductID = P.ProductID
JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID
JOIN Sales.Customer AS C ON SH.CustomerID = C.CustomerID
WHERE C.StoreID = @storeid
GROUP BY P.ProductID, P.Name
37
);
Example 4 (contd).
The following example invokes the function and
specifies customer ID 602.
SELECT * FROM Sales.ufn_SalesByStore (602);

Slide 9- 38
SQL/PSM: An Example
CREATE FUNCTION DEPT_SIZE (IN deptno INTEGER)
RETURNS VARCHAR[7]
DECLARE TOT_EMPS INTEGER;

SELECT COUNT (*) INTO TOT_EMPS


FROM SELECT EMPLOYEE WHERE DNO = deptno;
IF TOT_EMPS > 100 THEN RETURN “HUGE”
ELSEIF TOT_EMPS > 50 THEN RETURN “LARGE”
ELSEIF TOT_EMPS > 30 THEN RETURN “MEDIUM”
ELSE RETURN “SMALL”
ENDIF;

Slide 9- 39
SQL Persistent Stored Modules (SQL/PSM) (contd.)
• Assigment: Learn loop structures in PSM. How
is it expanded in SQL-Server and Oracle. Give
some examples.

40
V. Database Programming with Function Calls
• Known as an application programming interface
(API). The main advantage of using a function call
interface is that it makes it easier to access multiple
databases within the same application program, even if
they are stored under different DBMS packages.
• Embedded SQL enables the integration of SQL with a
general-purpose programming language. A DBMS-
specific preprocessor transforms the embedded SQL
statements into function calls in the host language. The
details of this translation vary across DBMS, and
therefore even though the source code can be compiled
to work with different DBMSs, the final executable works
only with one specific DBMS.

41
Client-Server Application

Client Server
Client Software

Database

Provides data to
client
Data Access Components
Requests data
Database
Sends data
User Server Running

Requests data
Database
Error Message
Client Software Server Down

DAC
(ODBC, OLE DB, Database
ADO, ADO.net)
ODBC
• Open Database Connectivity is a set of
Application Program Interface (API) functions
• Core functionality of ODBC:
• Database Connection
• Preparing and executing SQL statements
• Processing transactions
• Returning the result
• Recording and reporting errors
Working of ODBC

Client
(Application)
ODBC Relational
 Database
Client
(Application)
OLE DB
 Object linking and Embedding for Database is an
API based on COM (Component Object Model)
• It accesses different kinds of data

Database

Client ODBC
OLE DB
Applications Connection
ADO
ActiveX Data Object is a collection of objects,
which are used to access the database
• Uses of ADO:
• Connects to a data source
• Specifies a command to access a data source and
execute it
• Stores the returned data in cache for manipulation
• Updates the data source with the modified data in
the cache
ADO
Database

Client
Application
ADO.net
 Introduced with the Microsoft .net framework
ADO.net
 Introduced with the Microsoft .net framework

Stored
into

Database

ADO.net
Client Data access technology
Benefits of ADO.net
 Interoperability
 Performance
 Scalability
 Standardization
 Programmability
Basic components of ADO.net

• Connection
• Command
• DataReader
• DataAdapter
.Net Data Providers

.NET DATA
PROVIDERS
Establish connection with the databas

Retrieve and manipulate data in the databa


Summary
• A database may be accessed in an interactive mode
• Most often, however, data in a database is manipulate via
application programs
• Several methods of database programming:
– Embedded SQL
– Dynamic SQL
– Stored procedure and function

Slide 9- 54
Assigments:
• Dataset, DataTable, DataView: Properties, Method
and Events
• Creating DataTable, Add DataColumn objects, Add
rows to the table, Define primary key, Add
Constraint objects, …
• Connect and access database using SQL.Net Data
Provider (syntax and example)
• Connect and access database using OLEDB.Net Data
Provider (syntax and example)
• Connect and access database using LINQ
• Connect and access database using Client/Server
model 55

You might also like