Docsity

Database Connectivity-Database System Concepts-Lecture 08 Slides-Computer Science, Slides of Database Management Systems (DBMS)

Toggle sidebar
bg1
1
Computing & Information Sciences
Kansas State University
Mon, 11 Sep 2006CIS 560: Database System Concepts
Lecture 8 of 42
Monday, 11 September 2006
William H. Hsu
Department of Computing and Information Sciences, KSU
KSOL course page: http://snipurl.com/va60
Course web site: http://www.kddresearch.org/Courses/Fall-2006/CIS560
Instructor home page: http://www.cis.ksu.edu/~bhsu
Reading for Next Class:
Rest of Chapter 4, p. 151 onward, Silberschatz et al., 5th edition
Sections 5.1 – 5.2, Silberschatz et al., 5th edition
JDBC Primer (to be posted on Handouts page)
Database Connectivity: ODBC & JDBC
Notes: PS1 Solutions, MP2
Computing & Information Sciences
Kansas State University
Mon, 11 Sep 2006CIS 560: Database System Concepts
Basic Query Structure:
Review
zSQL is based on set and relational operations with certain
modifications and enhancements
zA typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P
Ai represents an attribute
Rirepresents a relation
Pis a predicate.
zThis query is equivalent to the relational algebra expression.
zThe result of an SQL query is a relation.
))(( 21,,, 21 mPAAA rrr
n
×
×
×
∏
Κ
Κ
σ
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Database Connectivity-Database System Concepts-Lecture 08 Slides-Computer Science and more Slides Database Management Systems (DBMS) in PDF only on Docsity!

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Lecture 8 of 42

Monday, 11 September 2006

William H. Hsu Department of Computing and Information Sciences, KSU

KSOL course page: http://snipurl.com/va Course web site: http://www.kddresearch.org/Courses/Fall-2006/CIS Instructor home page: http://www.cis.ksu.edu/~bhsu

Reading for Next Class: Rest of Chapter 4, p. 151 onward, Silberschatz et al. , 5 th^ edition Sections 5.1 – 5.2, Silberschatz et al. , 5th^ edition JDBC Primer (to be posted on Handouts page)

Database Connectivity: ODBC & JDBC

Notes: PS1 Solutions, MP

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Basic Query Structure:

Review

z SQL is based on set and relational operations with certain modifications and enhancements z A typical SQL query has the form:

select A 1 , A 2 , ..., An from r 1 , r 2 , ..., r (^) m where P

’ Ai represents an attribute ’ Ri represents a relation ’ P is a predicate. z This query is equivalent to the relational algebra expression.

z The result of an SQL query is a relation.

∏ A 1 , A 2 ,Κ, An ( σ P ( r 1 × r 2 ×Κ× rm ))

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Update of a View:

Review

Update of a View:

Review

z Create a view of all loan data in the loan relation, hiding the amount attribute create view branch_loan as select branch_name, loan_number from loan z Add a new tuple to branch_loan insert into branch_loan values (‘Perryridge’, ‘L-307’) This insertion must be represented by the insertion of the tuple (‘L-307’, ‘Perryridge’, null ) into the loan relation

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Embedded SQL Embedded SQL

z The SQL standard defines embeddings of SQL in a variety of programming languages such as C, Java, and Cobol. z A language to which SQL queries are embedded is referred to as a host language , and the SQL structures permitted in the host language comprise embedded SQL. z The basic form of these languages follows that of the System R embedding of SQL into PL/I. z EXEC SQL statement is used to identify embedded SQL request to the preprocessor EXEC SQL END_EXEC Note: this varies by language (for example, the Java embedding uses

SQL { …. }; )

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

ODBCODBC

z Open DataBase Connectivity(ODBC) standard ’ standard for application program to communicate with a database server. ’ application program interface (API) to Ö open a connection with a database, Ö send queries and updates, Ö get back results. z Applications such as GUI, spreadsheets, etc. can use ODBC

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

ODBC (Cont.) ODBC (Cont.)

z Each database system supporting ODBC provides a "driver" library that must be linked with the client program. z When client program makes an ODBC API call, the code in the library communicates with the server to carry out the requested action, and fetch results. z ODBC program first allocates an SQL environment, then a database connection handle. z Opens database connection using SQLConnect(). Parameters for SQLConnect: ’ connection handle, ’ the server to which to connect ’ the user identifier, ’ password z Must also specify types of arguments: ’ SQL_NTS denotes previous argument is a null-terminated string.

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

ODBC Code ODBC Code

z int ODBCexample() { RETCODE error; HENV env; / environment / HDBC conn; / database connection / SQLAllocEnv(&env); SQLAllocConnect(env, &conn); SQLConnect(conn, "aura.bell-labs.com", SQL_NTS, "avi", SQL_NTS, "avipasswd", SQL_NTS); { …. Do actual work … }

SQLDisconnect(conn); SQLFreeConnect(conn); SQLFreeEnv(env); }

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

ODBC Code (Cont.)ODBC Code (Cont.)

z Program sends SQL commands to the database by using SQLExecDirect z Result tuples are fetched using SQLFetch() z SQLBindCol() binds C language variables to attributes of the query result ’ When a tuple is fetched, its attribute values are automatically stored in corresponding C variables. ’ Arguments to SQLBindCol() Ö ODBC stmt variable, attribute position in query result Ö The type conversion from SQL to C. Ö The address of the variable. Ö For variable-length types like character arrays, ‹ The maximum length of the variable ‹ Location to store actual length when a tuple is fetched. ‹ Note: A negative value returned for the length field indicates null value z Good programming requires checking results of every function call for errors; we have omitted most checks for brevity.

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

ODBC Conformance LevelsODBC Conformance Levels

z Conformance levels specify subsets of the functionality defined by the standard. ’ Core ’ Level 1 requires support for metadata querying ’ Level 2 requires ability to send and retrieve arrays of parameter values and more detailed catalog information. z SQL Call Level Interface (CLI) standard similar to ODBC interface, but with some minor differences.

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

JDBC JDBC

z JDBC is a Java API for communicating with database systems supporting SQL z JDBC supports a variety of features for querying and updating data, and for retrieving query results z JDBC also supports metadata retrieval, such as querying about relations present in the database and the names and types of relation attributes z Model for communicating with the database: ’ Open a connection ’ Create a “statement” object ’ Execute queries using the Statement object to send queries and fetch results ’ Exception mechanism to handle errors

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

JDBC CodeJDBC 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:@aura.bell- labs.com:2000:bankdb", userid, passwd); Statement stmt = conn.createStatement(); … Do Actual Work …. stmt.close(); conn.close(); } catch (SQLException sqle) { System.out.println("SQLException : " + sqle); } }

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

JDBC Code (Cont.) JDBC Code (Cont.)

z Update to database try { stmt.executeUpdate( "insert into account values ('A-9732', 'Perryridge', 1200)"); } catch (SQLException sqle) { System.out.println("Could not insert tuple. " + sqle); } z Execute query and fetch and print results 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)); }

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Functions and ProceduresFunctions and Procedures

z SQL:1999 supports functions and procedures ’ Functions/procedures can be written in SQL itself, or in an external programming language ’ Functions are particularly useful with specialized data types such as images and geometric objects Ö Example: functions to check if polygons overlap, or to compare images for similarity ’ Some database systems support table-valued functions , which can return a relation as a result z SQL:1999 also supports a rich set of imperative constructs, including ’ Loops, if-then-else, assignment z Many databases have proprietary procedural extensions to SQL that differ from SQL:

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

SQL Functions SQL Functions

z Define a function that, given the name of a customer, returns the count of the number of accounts owned by the customer. create function account_count ( customer_name varchar (20)) returns integer begin declare a_count integer; select count ( * ) into a_count from depositor where depositor.customer_name = customer_name return a_count; end z Find the name and address of each customer that has more than one account. select customer_name, customer_street, customer_city from customer where account_ count ( customer_name ) > 1

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Table Functions Table Functions

z SQL:2003 added functions that return a relation as a result z Example: Return all accounts owned by a given customer create function accounts_of ( customer_name char (20) returns table ( account_number char (10), branch_name char (15), balance numeric (12,2)) return table ( select account_number, branch_name, balance from account where exists ( select * from depositor where depositor.customer_name = accounts_of.customer_name and depositor.account_number = account.account_number ))

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Table Functions (cont’d)Table Functions (cont’d)

z Usage select * from table ( accounts_of (‘Smith’))

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Procedural Constructs (Cont.) Procedural Constructs (Cont.)

z For loop ’ Permits iteration over all results of a query ’ Example: find total of all balances at the Perryridge branch

declare n integer default 0; for r as select balance from account where branch_name = ‘Perryridge’ do set n = n + r. balance end for

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Procedural Constructs (cont.) Procedural Constructs (cont.)

z Conditional statements ( if-then-else ) E.g. To find sum of balances for each of three categories of accounts (with balance <1000, >=1000 and <5000, >= 5000) if r. balance < 1000 then set l = l + r. balance elseif r. balance < 5000 then set m = m + r. balance else set h = h + r. balance end if z SQL:1999 also supports a case statement similar to C case statement z Signaling of exception conditions, and declaring handlers for exceptions declare out_of_stock condition declare exit handler for out_of_stock begin … .. signal out-of-stock end ’ The handler here is exit -- causes enclosing begin end to be exited

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

External Language Functions/ProceduresExternal Language Functions/Procedures

z SQL:1999 permits the use of functions and procedures written in other languages such as C or C++ z Declaring external language procedures and functions

create procedure account_count_proc( in customer_name varchar (20), out count integer ) language C external name ’ /usr/avi/bin/account_count_proc’

create function account_count( customer_name varchar (20)) returns integer language C external name ‘/usr/avi/bin/author_count’

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

External Language Routines (Cont.) External Language Routines (Cont.)

z Benefits of external language functions/procedures: ’ more efficient for many operations, and more expressive power z Drawbacks ’ Code to implement function may need to be loaded into database system and executed in the database system’s address space Ö risk of accidental corruption of database structures Ö security risk, allowing users access to unauthorized data ’ There are alternatives, which give good security at the cost of potentially worse performance ’ Direct execution in the database system’s space is used when efficiency is more important than security

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

The Power of Recursion The Power of Recursion

z Recursive views make it possible to write queries, such as transitive closure queries, that cannot be written without recursion or iteration. ’ Intuition: Without recursion, a non-recursive non-iterative program can perform only a fixed number of joins of manager with itself Ö This can give only a fixed number of levels of managers Ö Given a program we can construct a database with a greater number of levels of managers on which the program will not work ’ The next slide shows a manager relation and each step of the iterative process that constructs empl from its recursive definition. The final result is called the fixed point of the recursive view definition. z Recursive views are required to be monotonic. That is, if we add tuples to manger the view contains all of the tuples it contained before, plus possibly more

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Example of Fixed-Point ComputationExample of Fixed-Point Computation

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Advanced SQL FeaturesAdvanced SQL Features

z Create a table with the same schema as an existing table: create table temp_account like account z SQL:2003 allows subqueries to occur anywhere a value is required provided the subquery returns only one value. This applies to updates as well z SQL:2003 allows subqueries in the from clause to access attributes of other relations in the from clause using the lateral construct: select customer_name, num_accounts from customer , lateral ( select count (*) from account where account.customer_name = customer.customer_name ) as this_customer ( num_accounts )

Computing & Information Sciences CIS 560: Database System Concepts Mon, 11 Sep 2006 Kansas State University

Advanced SQL Features (cont’d)Advanced SQL Features (cont’d)

z Merge construct allows batch processing of updates. z Example: relation funds_received ( account_number, amount ) has batch of deposits to be added to the proper account in the account relation merge into account as A using ( select * from funds_received as F ) on (A .account_number = F.account_number ) when matched then update set balance = balance + F.amount