Beruflich Dokumente
Kultur Dokumente
Database System
Concepts, 6th Ed.
Silberschatz, Korth and Sudarshan
See www.db-book.com for conditions on
SQL
and ODBC
lEmbedded
SQL
5.*
lFetch
5.*
JDBC
nJDBC is a Java API for communicating with database
a connection
lCreate
a statement object
lExecute
5.*
JDBC Code
public static void JDBCexample(String dbid, String userid, String
passwd)
{
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@db.yale.edu:2000:univdb", userid,
passwd);
Statement stmt = conn.createStatement();
Do Actual Work .
stmt.close();
conn.close();
}
catch (SQLException sqle) {
System.out.println("SQLException : " + sqle);
}
}
Database System Concepts - 6th
5.*
try {
stmt.executeUpdate(
"insert into instructor values(77987, Kim, Physics,
98000)");
} catch (SQLException sqle)
{
System.out.println("Could not insert tuple. " + sqle);
}
nExecute query and fetch and print results
5.*
and rs.getString(1)
equivalent if dept_name is the first argument of
select result.
nDealing with Null values
lint
a = rs.getInt(a);
5.*
PREPARED STATEMENT
nPreparedStatement pStmt = conn.prepareStatement(
if name is DSouza?
5.*
SQL INJECTION
nSuppose query is constructed using
l"select
5.*
METADATA FEATURES
nResultSet metadata
nE.g., after executing query to get a ResultSet rs:
lResultSetMetaData
rsmd = rs.getMetaData();
5.*
METADATA (CONT)
nDatabase metadata
nDatabaseMetaData dbmd = conn.getMetaData();
5.*
conn.setAutoCommit(false);
explicitly
l
conn.commit();
conn.rollback();
or
5.*
cStmt2 = conn.prepareCall("{call
some procedure(?,?)}");
nHandling large object types
lgetBlob()
lassociate
parameterIndex, InputStream
inputStream).
Database System Concepts - 6th
5.*
SQLJ
nJDBC is overly dynamic, errors cannot be caught by
compiler
nSQLJ: embedded SQL in Java
l#sql
5.*
ODBC
n Open DataBase Connectivity(ODBC) standard
l
ODBC
n Was defined originally for Basic and C, versions available
5.*
ODBC (Cont.)
n Each database system supporting ODBC provides a
connection handle,
password
5.*
ODBC Code
n
int ODBCexample()
{
RETCODE error;
HENV
env;
/* environment */
HDBC
SQLAllocEnv(&env);
SQLAllocConnect(env, &conn);
SQLConnect(conn, db.yale.edu", SQL_NTS, "avi",
SQL_NTS, "avipasswd", SQL_NTS);
{ . Do actual work }
SQLDisconnect(conn);
SQLFreeConnect(conn);
SQLFreeEnv(env);
}
Database System Concepts - 6th
5.*
SQLExecDirect
nResult tuples are fetched using SQLFetch()
nSQLBindCol() binds C language variables to attributes of the
query result
lWhen
5.*
char deptname[80];
float salary;
int lenOut1, lenOut2;
HSTMT stmt;
char * sqlquery = "select dept_name, sum (salary)
from instructor
group by dept_name";
SQLAllocStmt(conn, &stmt);
error = SQLExecDirect(stmt, sqlquery, SQL_NTS);
if (error == SQL SUCCESS) {
SQLBindCol(stmt, 1, SQL_C_CHAR, deptname , 80,
&lenOut1);
SQLBindCol(stmt, 2, SQL_C_FLOAT, &salary, 0 , &lenOut2);
while (SQLFetch(stmt) == SQL_SUCCESS) {
printf (" %s %g\n", deptname, salary);
}
}
Database System
Concepts - 6
5.*
Silberschatz, Korth and
SQLFreeStmt(stmt,
SQL_DROP);
th
n To prepare a statement
SQLBindParameter(stmt, <parameter#>,
type information and value omitted for
simplicity..)
n
5.*
SQLTransact(conn, SQL_COMMIT) or
SQLTransact(conn, SQL_ROLLBACK)
5.*
Core
5.*
ADO.NET
n API designed for Visual Basic .NET and C#, providing database
EMBEDDED SQL
nThe SQL standard defines embeddings of SQL in a variety
5.*
EXAMPLE QUERY
nFrom within a host language, find the ID and name of
EXEC SQL
declare c cursor for
select ID, name
from student
where tot_cred > :credit_amount
END_EXEC
5.*
5.*
update instructor
set salary = salary + 100
where current of c
5.*
5.*
Permits definition of procedures in SQL, with if-thenelse statements, for and while loops, etc.
n Stored Procedures
l
5.*
including
lLoops,
if-then-else, assignment
5.*
SQL FUNCTIONS
nDefine a function that, given the name of a department,
5.*
TABLE FUNCTIONS
nSQL:2003 added functions that return a relation as a
result
nExample: Return all accounts owned by a given customer
select *
from table (instructors_of (Music))
Database System Concepts - 6th
5.*
SQL Procedures
n The dept_count function could instead be written as
procedure:
create procedure dept_count_proc (in dept_name
varchar(20),
out d_count
integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name =
dept_count_proc.dept_name
end
n Procedures can be invoked either from an SQL procedure
or from embedded SQL, using the call statement.
declare d_count integer;
call dept_count_proc( Physics, d_count);
Procedures and functions can be invoked also from
dynamic SQL
Database
Concepts - 6 allows more than one
5.*
Silberschatz,
Korth and
n System
SQL:1999
function/procedure
of the
th
Procedural Constructs
n
5.*
PROCEDURAL CONSTRUCTS
(CONT.)
nFor loop
lPermits
lExample:
5.*
exceptions
declare out_of_classroom_seats condition
declare exit handler for out_of_classroom_seats
begin
.. signal out_of_classroom_seats
end
The handler here is exit -- causes enclosing begin..end to
Database System
Concepts
-6
5.*
Silberschatz, Korth and
be
exited
l
th
EXTERNAL LANGUAGE
FUNCTIONS/PROCEDURES
nSQL:1999 permits the use of functions and procedures
5.*
n Drawbacks
l
5.*
sandbox techniques
4that
5.*
Triggers
5.*
TRIGGERS
nA trigger is a statement that is executed
5.*
TRIGGER EXAMPLE
nE.g. time_slot_id is not a primary key of timeslot, so we
integrity constraints
create trigger timeslot_check1 after insert on section
referencing new row as nrow
for each row
when (nrow.time_slot_id not in (
select time_slot_id
from time_slot)) /* time_slot_id not present in
time_slot */
begin
rollback
end;
Database System Concepts - 6th
5.*
5.*
attributes
l E.g., after update of takes on grade
n Values of attributes before and after an update can be
referenced
l referencing old row as : for deletes and
updates
l referencing new row as : for inserts and
updates
n Triggers can be activated before an event, which can
serve as extra constraints. E.g. convert blank grades
to null.
create trigger setnull_trigger before update of
takes
referencing new row as nrow
for each row
when
(nrow.grade = 5.*)
Database System Concepts
-6
Silberschatz, Korth and
th
Trigger to Maintain
credits_earned value
n create trigger credits_earned after update of takes
on (grade)
referencing new row as nrow
referencing old row as orow
for each row
when nrow.grade <> F and nrow.grade is not null
and (orow.grade = F or orow.grade is null)
begin atomic
update student
set tot_cred= tot_cred +
(select credits
from course
where course.course_id= nrow.course_id)
where student.id = nrow.id;
end;
5.*
instead of
for
lUse
5.*
department)
lReplicating
cases
lDefine
lCarry
5.*
when
lloading
lreplicating
lTrigger
execution
5.*
Recursive Queries
5.*
RECURSION IN SQL
nSQL:1999 permits recursive view definition
Without recursion, a non-recursive noniterative program can perform only a fixed number of
joins of prereq with itself
4This
5.*
lEach
5.*
EXAMPLE OF FIXED-POINT
COMPUTATION
5.*
5.*
RANKING
nRanking is done in conjunction with an order by specification.
nSuppose we are given a relation
student_grades(ID, GPA)
giving the grade-point average of each student
nFind the rank of each student.
order
select ID, rank() over (order by GPA desc) as s_rank
from student_grades
order by s_rank
nRanking may leave gaps: e.g. if 2 students have the same top
would be 2
Database System Concepts - 6th
5.*
Ranking
n Ranking can be done using basic SQL aggregation, but
5.*
Ranking (Cont.)
n Ranking can be done within partition of the data.
n Find the rank of students within each department.
5.*
RANKING (CONT.)
nOther ranking functions:
lpercent_rank
done)
lcume_dist
4
(cumulative distribution)
lrow_number
(non-deterministic in presence of
duplicates)
nSQL:1999 permits the user to specify nulls first or nulls
last
select ID,
rank ( ) over (order by GPA desc nulls last) as
s_rank
from student_grades
5.*
RANKING (CONT.)
nFor a given constant n, the ranking the function ntile(n)
5.*
WINDOWING
nUsed to smooth out random variations.
nE.g., moving average: Given sales values for each date,
calculate for each date the average of the sales on that day,
the previous day, and the next day
nWindow specification in SQL:
lGiven relation sales(date, value)
select date, sum(value) over
(order by date between rows 1 preceding and 1
following)
from sales
5.*
WINDOWING
nExamples of other window specifications:
lbetween
5.*
WINDOWING (CONT.)
nCan do windowing within partitions
nE.g., Given a relation transaction (account_number,
5.*
OLAP**
5.*
Measure attributes
4
Dimension attributes
4
5.*
EXAMPLE SALES
RELATION
..
.
..
.
..
5.*
.
..
.
Data Cube
nA data cube is a multidimensional generalization of a
cross-tab
nCan have n dimensions; we show 3 below
nCross-tabs can be used as views on a data cube
5.*
Hierarchies on Dimensions
nHierarchy on dimension attributes: lets dimensions to be
5.*
5.*
Cross-tabs
nCross-tabs can be
represented as relations
We use the value all is
used to represent
aggregates.
The SQL standard
actually uses null values in
place of all despite
confusion with regular null
values.
5.*
EXTENDED AGGREGATION TO
SUPPORT OLAP
nThe cube operation computes union of group bys on every subset
5.*
5.*
replace
such nulls by a value such as all
lE.g.,
5.*
5.*
clause
lEach
5.*
called
n Slicing: creating a cross-tab for fixed values only
l
granularity
n Drill down: The opposite operation - that of moving
5.*
OLAP Implementation
n The earliest OLAP systems used multidimensional arrays
5.*
5.*
End of Chapter
Database System
Concepts, 6th Ed.
Silberschatz, Korth and Sudarshan
See www.db-book.com for conditions on
FIGURE 5.22
5.*
FIGURE 5.23
5.*
FIGURE 5.24
5.*
manager(employee_name, manager_name)
nFind all employee-manager pairs, where the employee reports
5.*
5.*