Embedded SQL and Dynamic SQL-Database System Concepts-Lecture 07 Slides-Computer Science, Slides of Database Management Systems (DBMS)

Embedded SQL and Dynamic SQL, Assertions, Authorization, Cursors, Basic Query Structure, Update of a View, Predicate, Read, Insert, Update, Delete, Index, Resources, Alteration, Drop, Specification, Grant, Privilege, Administrator, All Privileges, Revoking Authorization, Embedded SQL, Host Language, Fetch, SQLSTATE, Communication Area, Close, Updates Through Cursors, Dynamic SQL, ODBC and JDBC, Application-program Interface, Database Server, Open Database Connectivity, GUI, Library, SQLConnect()

Typology: Slides

2011/2012

Uploaded on 01/31/2012

beatryx
beatryx 🇺🇸

4.6

(16)

289 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Computing & Information Sciences
Kansas State University
Friday, 08 Sep 2006CIS 560: Database System Concepts
Lecture 7 of 42
Friday, 08 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:
Sections 4.5 – 4.6, p. 137 – 151, Silberschatz et al., 5th edition
MySQL Primer info (to be posted on Handouts page)
Embedded SQL and Dynamic SQL
Notes: Assertions, Authorization, Cursors
Computing & Information Sciences
Kansas State University
Friday, 08 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 Embedded SQL and Dynamic SQL-Database System Concepts-Lecture 07 Slides-Computer Science and more Slides Database Management Systems (DBMS) in PDF only on Docsity!

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

Lecture 7 of 42

Friday, 08 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: Sections 4.5 – 4.6, p. 137 – 151, Silberschatz et al. , 5th^ edition MySQL Primer info (to be posted on Handouts page)

Embedded SQL and Dynamic SQL

Notes: Assertions, Authorization, Cursors

Computing & Information Sciences CIS 560: Database System Concepts Friday, 08 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 Friday, 08 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 Friday, 08 Sep 2006 Kansas State University

AssertionsAssertions

z An assertion is a predicate expressing a condition that we wish the database always to satisfy. z An assertion in SQL takes the form create assertion <assertion-name> check z When an assertion is made, the system tests it for validity, and tests it again on every update that may violate the assertion ’ This testing may introduce a significant amount of overhead; hence assertions should be used with great care. z Asserting for all X , P ( X ) is achieved in a round-about fashion using not exists X such that not P ( X )

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

Authorization Authorization

Forms of authorization on parts of the database:

z Read - allows reading, but not modification of data. z Insert - allows insertion of new data, but not modification of existing data. z Update - allows modification, but not deletion of data. z Delete - allows deletion of data.

Forms of authorization to modify the database schema (covered in Chapter 8): z Index - allows creation and deletion of indices. z Resources - allows creation of new relations. z Alteration - allows addition or deletion of attributes in a relation. z Drop - allows deletion of relations.

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

Authorization Specification in SQLAuthorization Specification in SQL

z The grant statement is used to confer authorization grant on to z is: ’ a user-id ’ public , which allows all valid users the privilege granted ’ A role (more on this in Chapter 8) z Granting a privilege on a view does not imply granting any privileges on the underlying relations. z The grantor of the privilege must already hold the privilege on the specified item (or be the database administrator).

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

Privileges in SQLPrivileges in SQL

z select: allows read access to relation,or the ability to query using the view ’ Example: grant users U 1 , U 2 , and U 3 select authorization on the branch relation: grant select on branch to U 1 , U 2 , U 3 z insert : the ability to insert tuples z update : the ability to update using the SQL update statement z delete : the ability to delete tuples. z all privileges : used as a short form for all the allowable privileges z more in Chapter 8

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

Revoking Authorization in SQL Revoking Authorization in SQL

z The revoke statement is used to revoke authorization. revoke on from z Example: revoke select on branch from U 1 , U 2 , U 3 z <privilege-list> may be all to revoke all privileges the revokee may hold. z If <revokee-list> includes public, all users lose the privilege except those granted it explicitly. z If the same privilege was granted twice to the same user by different grantees, the user may retain the privilege after the revocation. z All privileges that depend on the privilege being revoked are also revoked.

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

Embedded SQL (Cont.)Embedded SQL (Cont.)

z The open statement causes the query to be evaluated EXEC SQL open c END_EXEC z The fetch statement causes the values of one tuple in the query result to be placed on host language variables. EXEC SQL fetch c into : cn, :cc END_EXEC Repeated calls to fetch get successive tuples in the query result z A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to ‘02000’ to indicate no more data is available z The close statement causes the database system to delete the temporary relation that holds the result of the query. EXEC SQL close c END_EXEC Note: above details vary with language. For example, the Java embedding defines Java iterators to step through result tuples.

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

Updates Through Cursors Updates Through Cursors

„ Can update tuples fetched by cursor by declaring that the cursor is for update declare c cursor for select * from account where branch_name = ‘Perryridge’ for update „ To update tuple at the current location of cursor c update account set balance = balance + 100 where current of c

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

Dynamic SQLDynamic SQL

z Allows programs to construct and submit SQL queries at run time. z Example of the use of dynamic SQL from within a C program.

**char *** sqlprog = “ update account set balance = balance * 1. where account_number = ?” EXEC SQL prepare dynprog from :sqlprog; char account [10] = “A-101”; EXEC SQL execute dynprog using :account; z The dynamic SQL program contains a ?, which is a place holder for a value that is provided when the SQL program is executed.

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

ODBC and JDBC ODBC and JDBC

z API (application-program interface) for a program to interact with a database server z Application makes calls to ’ Connect with the database server ’ Send SQL commands to the database server ’ Fetch tuples of result one-by-one into program variables z ODBC (Open Database Connectivity) works with C, C++, C#, and Visual Basic z JDBC (Java Database Connectivity) works with Java

Computing & Information Sciences CIS 560: Database System Concepts Friday, 08 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 Friday, 08 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 Friday, 08 Sep 2006 Kansas State University

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

z Main body of program 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\n", branchname, balance); } } SQLFreeStmt(stmt, SQL_DROP);

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

More ODBC FeaturesMore ODBC Features

z Prepared Statement ’ SQL statement prepared: compiled at the database ’ Can have placeholders: E.g. insert into account values(?,?,?) ’ Repeatedly executed with actual values for the placeholders z Metadata features ’ finding all the relations in the database and ’ finding the names and types of columns of a query result or a relation in the database. z By default, each SQL statement is treated as a separate transaction that is committed automatically. ’ Can turn off automatic commit on a connection Ö SQLSetConnectOption(conn, SQL_AUTOCOMMIT, 0)} ’ transactions must then be committed or rolled back explicitly by Ö SQLTransact(conn, SQL_COMMIT) or Ö SQLTransact(conn, SQL_ROLLBACK)

Computing & Information Sciences CIS 560: Database System Concepts Friday, 08 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 Friday, 08 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 Friday, 08 Sep 2006 Kansas State University

JDBC Code DetailsJDBC Code Details

z Getting result fields: ’ rs.getString(“branchname”) and rs.getString(1) equivalent if branchname is the first argument of select result. z Dealing with Null values int a = rs.getInt(“a”); if (rs.wasNull()) Systems.out.println(“Got null value”);

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

Procedural Extensions and

Stored Procedures

Procedural Extensions and

Stored Procedures

z SQL provides a module language ’ Permits definition of procedures in SQL, with if-then-else statements, for and while loops, etc. ’ more in Chapter 9 z Stored Procedures ’ Can store procedures in the database ’ then execute them using the call statement ’ permit external applications to operate on the database without knowing about internal details z These features are covered in Chapter 9 (Object Relational Databases)