Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Database System ConceptsChapter 8(+4): Application Design and Development
Departamento de Engenharia InformaticaInstituto Superior Tecnico
1st Semester2010/2011
Slides (fortemente) baseados nos slides oficiais do livro“Database System Concepts”c©Silberschatz, Korth and Sudarshan.
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Outline
1 Database Applications
2 Embedded SQL
3 Database APIsODBCJDBC
4 Web Database ApplicationsThe World Wide WebDatabases and the Web
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Outline
1 Database Applications
2 Embedded SQL
3 Database APIs
4 Web Database Applications
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
User Interfaces and Tools
Most database users do not use a query language like SQL
FormsGraphical user interfacesReport generatorsData analysis tools
Applications can embed or execute SQL
Many interfaces are Web-based
Client-side: Javascript, Applets, ...Server-side: Java Server Pages (JSP), Active Server Pages(ASP), ...
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Application Architectures
Applications can be built using one of two architectures:
Two tier model
Application programs running at user site communicatedirectly with the database
Three tier model
User programs running at user sites communicate with anapplication serverThe application server in turn communicates with thedatabase
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Two-Tier Architecture
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Three-Tier Architecture
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Two-Tier Web-Based Architecture
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Two-tier Model
Example: Java code runs at client site and uses JDBC tocommunicate with the server
Benefits:
flexible, need not be restricted to predefined queries
Problems:
Security: all database operations possibleMore code shipped to clientNot appropriate across organizations, or in large ones likeuniversities
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Three-tier Model
Example: Web client + Java Servlet using JDBC to talkwith database server
Benefits:
Security handled by application at serverSimple clientDistributed system
Problems:
Performance issuesNetwork-dependentOnly packaged transactions
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Outline
1 Database Applications
2 Embedded SQL
3 Database APIs
4 Web Database Applications
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Embedded SQL
The SQL standard defines embeddings of SQL in a varietyof programming languages such as C, Java, and Cobol
A language to which SQL queries are embedded is referredto as a host language, and the SQL structures permittedin the host language comprise embedded SQL
EXEC SQL statement is used to identify embedded SQLrequest to the SQL preprocessor
EXEC SQL <embedded SQL statement>;
Note: this varies by language (for example, the Javaembedding uses #SQL { ... };)
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Embedded SQL Example
Find the names and cities of customers with more than a givenamount of dollars in their accounts
EXEC SQL BEGIN DECLARE SECTION;
double amount;char name[50];char city [50];EXEC SQL END DECLARE SECTION;
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Embedded SQL Example (cont.)
Find the names and cities of customers with more than a givenamount of dollars in their accounts
amount = 100;
EXEC SQL
declare c cursor for
select depositor .customer name, customer cityfrom depositor, customer, accountwhere depositor .customer name = customer .customer name
and depositoraccount number = account.account numberand account.balance > :amount;
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Embedded SQL Example (cont.)
Find the names and cities of customers with more than a givenamount of dollars in their accounts
EXEC SQL open c;
do {EXEC SQL fetch c into :name, :city;
if (SQLCODE ! = 0) break;
printf("%s, %s\n", name, city);
} while (1);
EXEC SQL close c;
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Updates through Cursors
Can update tuples fetched by cursor by declaring that thecursor is for update
declare c cursor for
select ∗from accountwhere branch name = ’Perryridge’
for update
To update the tuple at the current location of cursor c
update accountset balance = balance + 100where current of c
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
Dynamic SQL
Allows programs to construct and submit SQL queries atrun time
Example:
char sqlprog [100] = "update account "
"set balance = balance * 1.05 "
"where account number = ?";
EXEC SQL prepare dynprog from :sqlprog;
char account[10] = ”A-101”;EXEC SQL execute dynprog using :account;
The dynamic SQL program contains a “?”, which is aplace holder for a value that is provided when the SQLprogram is executed
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
Outline
1 Database Applications
2 Embedded SQL
3 Database APIsODBCJDBC
4 Web Database Applications
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
Database APIs
API (application-program interface) for a program tointeract with a database server
Application makes calls to
Connect with the database serverSend SQL commands to the database serverFetch tuples of result one-by-one into program variables
ODBC (Open Database Connectivity) works with C, C++,C#, ...
JDBC (Java Database Connectivity) works with Java
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
ODBC
Open DataBase Connectivity (ODBC) standard
Standard for application programs to communicate with adatabase serverApplication program interface (API) to
open a connection with a database,send queries and updates,get back results.
Applications such as GUI, spreadsheets, etc. can useODBC
Each database system supporting ODBC provides a driverlibrary that must be linked with the client program.
When client program makes an ODBC API call, the codein the library communicates with the server to carry outthe requested action, and fetch results.
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
Connecting to the Database
int ODBCexample(){
RETCODE error;HENV env; /*environment*/HDBC conn; /*database connection*/SQLAllocEnv(&env);SQLAllocConnect(env, conn);SQLConnect(conn, ”tagus.ist.utl .pt”, SQL NTS,
”user”, SQL NTS, ”userpasswd”, SQL NTS);
/*program code*/
SQLDisconnect(conn);SQLFreeConnect(conn);SQLFreeEnv(env);
}
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
Executing SQL Statements
char branchname[80];float balance;int lenOut1, lenOut2;HSTMT stmt;
SQLAllocStmt(conn, &stmt);char sqlquery [] = "select branch name, sum(balance)
from account group by branch name";
error = SQLExecDirect(stmt, sqlquery, SQL NTS);
if (error == SQL SUCCESS) {SQLBindCol(stmt, 1, SQL C CHAR, branchname, 80, &lenOut1);SQLBindCol(stmt, 2, SQL C FLOAT, &balance, 0 , &lenOut2);while (SQLFetch(stmt) >= SQL SUCCESS) {
printf ("%s %g", branchname, balance);}
}SQLFreeStmt(stmt, SQL DROP);
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
More ODBC Features
Prepared Statements
SQL statements compiled at the database
insert into account values(?,?,?)
Repeatedly executed with actual values for theplaceholders (“?”)
Metadata features
finding all the relations in the database andfinding the names and types of columns of a query resultor a relation in the database.
Control over transactions
Can turn off automatic commit on a connectiontransactions must then be committed or rolled backexplicitly
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
JDBC
JDBC is a Java API for communicating with databasesystems supporting SQL
JDBC supports a variety of features for querying andupdating data, and for retrieving query results
JDBC also supports metadata retrieval, such as queryingabout relations present in the database and the names andtypes of relation attributes
Model for communicating with the database:
Open a connectionCreate a statement objectExecute queries using the statement object to send queriesand fetch resultsException mechanism to handle errors
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
Connecting to the Database
public static void JDBCexample(String userid,String passwd){
try {Class.forName(“com.mysql.jdbc.Driver”);Connection conn = DriverManager.getConnection(
“jdbc:mysql://tagus.ist.utl.pt/database”, userid, passwd);Statement stmt = conn.createStatement();
/*program code*/
stmt.close();
conn.close();
}catch (SQLException sqle) {
System.out.println("SQLException: "+ sqle);}
}
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
Executing SQL Statements
ResultSet rset = stmt.executeQuery(
"select branch name, avg(balance)
from account
group by branch name");
while (rset.next()){
System.out.println(rset.getString(“branch name”)+ ‘‘ ’’ + rset.getFloat(2));
}
try {stmt.executeUpdate(
"insert into account values(’A-9732’, ’Perryridge’, 1200)");
} catch (SQLException sqle) {System.out.println("Could not insert tuple. "+ sqle);
}
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
ODBC
JDBC
Web DatabaseApplications
Prepared Statements
PreparedStatement s;s = conn.prepareStatement (
"insert into account values(?,?,?)");
s.setString(1, “A-9732”);s.setString(2, “Perryridge”);s.setFloat(3, 1200);s.executeUpdate();
s.close();
Plus all the other features of ODBC...
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Outline
1 Database Applications
2 Embedded SQL
3 Database APIs
4 Web Database ApplicationsThe World Wide WebDatabases and the Web
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
The World Wide Web
The Web is a distributed information system based onhypertext
Most Web documents are hypertext documents formattedvia the HyperText Markup Language (HTML)
HTML documents contain
text along with font specifications, and other formattinginstructionshypertext links to other documents, which can beassociated with regions of the text.forms, enabling users to enter data which can then be sentback to the Web server
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
HTML and HTTP
HTML provides formatting, hypertext link, and imagedisplay features.
HTML also provides input featuresSelect from a set of options
Pop-up menus, radio buttons, check lists
Enter values
Text boxes
Filled in input sent back to the server, to be acted upon byan executable at the server
HyperText Transfer Protocol (HTTP) used forcommunication with the Web server
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Sample HTML Source Code
<html><body>
<table border cols = 3><tr><td>A-101</td><td>Downtown</td><td>500</td></tr><tr><td>A-102</td><td>Perryridge</td><td>400</td></tr><tr><td>A-201</td><td>Brighton</td><td>900</td></tr>
</table><center>The <i>account</i> relation</center>
<form action="BankQuery" method=get>Select account/loan and enter number<br><select name="type">
<option value="account" selected>Account</option><option value="Loan">Loan</option>
</select><input type=text size=5 name="number"><input type=submit value="submit">
</form></body>
</html>
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Sample HTML Display
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Uniform Resources Locators
In the Web, functionality of pointers is provided byUniform Resource Locators (URLs).
URL example:
http://dev.mysql.com/doc/refman/5.0/en/index.html
The first part indicates how the document is to be accessedThe second part gives the unique name of a machine onthe InternetThe rest of the URL identifies the document within themachine
The local identification can be:
The path name of a file on the machine, orAn identifier (path name) of a program, plus arguments tobe passed to the programE.g.: http://www.google.pt/search?hl=pt-PT&q=mysql
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Web Servers
A Web server can easily serve as a front end to a variety ofinformation services
The document name in a URL may identify an executableprogram, that, when run, generates a HTML document
When a HTTP server receives a request for such adocument, it executes the program, and sends back theHTML document that is generatedThe Web client can pass extra arguments with the name ofthe document
To install a new service on the Web, one simply needs tocreate and install an executable that provides that service.
The Web browser provides a graphical user interface to theinformation service
Common Gateway Interface (CGI): a standard interfacebetween web and application server
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
HTTP and Sessions
The HTTP protocol is connectionless
That is, once the server replies to a request, the servercloses the connection with the client, and forgets all aboutthe requestIn contrast, Unix logins, and JDBC/ODBC connectionsstay connected until the client disconnects
retaining user authentication and other information
Motivation: reduces load on server
operating systems have tight limits on number of openconnections on a machine
Information services need session information
E.g. user authentication should be done only once persession
Solution: use a cookie
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Sessions and Cookies
A cookie is a small piece of text containing identifyinginformation
Sent by server to browser on first interactionSent by browser to the server that created the cookie onfurther interactions
part of the HTTP protocol
Server saves information about cookies it issued, and canuse it when serving a request
E.g., authentication information, and user preferences
Cookies can be stored permanently or for a limited time
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Web Interfaces to Databases
Web browsers have become the de-facto standard userinterface to databases
Enable large numbers of users to access databases fromanywhereAvoid the need for downloading/installing specialized code,while providing a good graphical user interfaceExamples: banks, airline and rental car reservations,university course registration and grading, etc.
However, static HTML documents are limited:
Cannot customize fixed Web documents for individualusers;Problematic to update Web documents, especially ifmultiple Web documents replicate data.
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Dynamic Generation of Web Documents
Solution: generate Web documents dynamically from datastored in a database
Can tailor the display based on user information stored inthe database
Example: tailored ads, tailored weather and local news, ...
Displayed information is up-to-date
Example: stock market information, prices, ...
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Common Gateway Interface (CGI)
Standard protocol for interfacing external applicationsoftware with an information server
Certain locations are defined to be served by a CGIprogram
Whenever a request to a matching URL is received, thecorresponding program is called
However, the overhead of spawning new processes forevery request can be overwhelming
Solution:
use compiled languagesuse client side scriptingintegrate language interpreters into the serveroptimize the server (use caching, ...)
Note: all this solutions have both advantages and disadvantages
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Servlets
Java Servlet specification defines an API forcommunication between the Web server and applicationprogram
E.g. methods to get parameter values and to send HTMLtext back to client
Application program (also called a servlet) is loaded intothe Web server
Two-tier modelEach request spawns a new thread in the Web server
thread is closed once the request is serviced
Servlet API provides a getSession() methodSets a cookie on first interaction with browser, and uses itto identify session on further interactionsProvides methods to store and look-up per-sessioninformation
E.g. user name, preferences, ...
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Example Servlet Code
Public class BankQueryServlet extends HttpServlet {public void doGet(HttpServletRequest request,
HttpServletResponse result)throws ServletException, IOException {
String type = request.getParameter(“type′′);String number = request.getParameter(“number ′′);
/*...code to find the loan amount/account balance...*//*...using JDBC to communicate with the database...*//*...we assume the value is stored in the variable balance...*/
result.setContentType(“text/html ′′);PrintWriter out = result.getWriter();out.println(“ < HEAD >< TITLE > QueryResult < /TITLE >< /HEAD >′′);out.println(“ < BODY >′′);out.println(“Balanceon′′ + type + number + “ =′′ +balance);out.println(“ < /BODY >′′);out.close();
}}
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Server-Side Scripting
Server-side scripting simplifies the task of connecting adatabase to the Web
Define a HTML document with embedded executablecode/SQL queries.Input values from HTML forms can be used directly in theembedded code/SQL queries.When the document is requested, the Web server executesthe embedded code/SQL queries to generate the actualHTML document.
Numerous server-side scripting languages
JSP, Server-side Javascript, PHP, Jscript, ...General purpose scripting languages: Perl, Python, ...
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Client Side Scripting and Applets
Browsers can fetch certain scripts (client-side scripts) orprograms along with documents, and execute them in“safe mode” at the client site
JavascriptMacromedia Flash and Shockwave for animation/gamesVRMLApplets
Client-side scripts/programs allow documents to be active
E.g., animation by executing programs at the local siteE.g. ensure that values entered by users satisfy somecorrectness checksPermit flexible interaction with the user.
Executing programs at the client site speeds upinteraction by avoiding many round trips to server
DatabaseSystem
Concepts
DatabaseApplications
EmbeddedSQL
Database APIs
Web DatabaseApplications
The World WideWeb
Databases andthe Web
Client Side Scripting and Security
Security mechanisms needed to ensure that maliciousscripts do not cause damage to the client machine
Easy for limited capability scripting languages, harder forgeneral purpose programming languages like Java
Example: Java’s security system ensures that the Javaapplet code does not make any system calls directly
Disallows dangerous actions such as file writesNotifies the user about potentially dangerous actions, andallows the option to abort the program or to continueexecution