System Aspects of SQL SQL Environment: Introduction SQL

Transcription

System Aspects of SQL SQL Environment: Introduction SQL
SQL Environment: Introduction
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
System Aspects of SQL
SQL Environment
User Access Control
SQL in Programming Environment
Embedded SQL
SQL and Java
Transactions (Programmers View)
SQL server
- Supports operations on database elements
- Typically runs on large host machine
SQL client
- Supports user connections to server
- Runs on (different) host machine
Connection
- Channel between client and server
7.2
SQL Environment: Module Types
Session
Generic SQL Interface:
- All SQL operations performed while connection open
- Current catalog, current schema , authorized user
SQL Environment
SQL Server
SQL agent
Connection
Session
SQL Client
Application
- Module: application program
- SQL agent: executionof module
7.3
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL Environment: Introduction
- Module: each query or statement
Embedded SQL:
- SQL statements within host-language program
- SQL statements pre-processed to function calls
- Calls executed at run-time
True modules:
- Collection of stored procedures
- Host language code, SQL code
7.4
1
User Access Control: Introduction
User
Secrecy:
- Outside schema, handling implementation dependent
- Identification by Authorization ID (user name)
Role
-
Defines user group
Inside schema, handling via SQL statements
Identification by Authorization ID (role name)
All users: special role PUBLIC
Examples:
CREATE
CREATE
CREATE
CREATE
ROLE
ROLE
ROLE
ROLE
Customer;
Secretary WITH ADMIN Klaus;
Movie_staff;
Shop_owner;
7.5
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL Environment: Privileges
- Users should not be able to see things they are not
supposed to.
- e.g., A student can’t see other students’ grades.
Integrity:
- Users should not be able to modify things they are not
supposed to.
- e.g., Only instructors can assign grades.
Availability:
- Users should be able to see and modify things they are
allowed to.
7.6
User Access Control: Privileges
Security policy specifies authorization
Security mechanism enforces a security policy
Privileges
Two mechanisms at DBMS level
Discretionary access control
- Concept of privileges for objects (tables and views)
- Mechanisms for giving and revoking users privileges
Mandatory access control
-
System-wide policies for DBS
DB object have security class
Rules on security classes govern access
Used for specialized (e.g., military) applications
7.7
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
User Access Control: Introduction
- Right to perform SQL statement type on objects
- Assigned to roles (authorization IDs)
- Creator of object: all privileges
- DBMS: management of privileges and access rights
Privilege types:
-
SELECT on table or view
INSERT on table or view
DELETE on table or view
UPDATE on table or view
REFERENCES: right to refer to relation in constraint
USAGE: (SQL-92) right to use specified domain
ALL PRIVILEGES: short form for all privileges
7.8
2
User Access Control: Privileges
Example
Grant privilege
INSERT INTO Format(name)
SELECT format
FROM Tape t
WHERE t.format NOT IN (SELECT name
FROM format);
Privileges:
- SELECT on Tape
- SELECT on Format
- INSERT on Format
7.9
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
User Access Control: Privileges
GRANT <privileges> ON <object>
TO <users> [WITH GRANT OPTION]
- GRANT OPTION: Right to pass privilege on to other users
- Only owner can execute CREATE, ALTER, and DROP
Privilege to SELECT particular columns in a table
GRANT <privileges>
ON <tablename(<attributenames>)>
TO <users> [WITH GRANT OPTION]
7.10
User Access Control: Privileges on views
Examples:
Creator has privilege on view if privilege on all
underlying tables
GRANT INSERT, SELECT ON
Movie
TO Klaus
Klaus can query Movie or insert tuples into it.
GRANT DELETE ON Movie TO shop_owner WITH GRANT OPTION
Anna can delete tuples, and also authorize others to do so
GRANT UPDATE (pricePDay) ON Movie TO movie_staff
Staff can update (only) the price field of Movie tuples
GRANT SELECT ON MovieView
TO Customers
This does NOT allow the customers to query Movie directly!
7.11
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
User Access Control: Privileges
Creator loses SELECT privilege on underlying table
⇒ view is dropped
Creator loses a privilege on underlying table ⇒
creator loses privilege on view
Creator loses a privilege held with grant option on
underlying table ⇒ users who were granted that
privilege on the view lose privilege on view
7.12
3
User Access Control: Privileges
User Access Control: Examples
Revoke privilege
REVOKE <privileges>
ON <object>
FROM <users> RESTRICT
- RESTRICT: only revoke if non of the privileges have been
granted by these users
- Privilege given from different users – must be revoked
from all users to loose privilege
7.13
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
Core
SQL:1999
User Access Control: Examples
Owner: GRANT Update ON Movie TO Anna;
owner
Klaus
Anna
Movie
Priv
Priv
Priv
Owner: REVOKE Update ON Movie FROM Klaus RESTRICT;
owner
Klaus
Movie
Anna
Priv
Priv
7.14
User Access Control: Privileges
GRANT Update ON Movie TO Anna;
owner
Klaus
Anna
Movie
Priv
Priv
Priv
Grant
Owner: REVOKE Update ON Movie FROM Klaus RESTRICT;
owner
Klaus
Anna
Movie
Priv
Priv
Priv
Grant
Command fails !
7.15
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
Owner: GRANT Update ON Movie TO Klaus WITH GRANT OPTION;
Klaus:
Owner: GRANT Update ON Movie TO Klaus;
Revoke privilege
enhanced
SQL:1999
REVOKE [GRANT OPTION FOR] <privileges>
ON <object>
FROM <users> {RESTRICT | CASCADE}
- CASCADE: revoke from all users that have been granted
the privilege by these users
- RESTRICT: only revoke if non of the privileges have been
granted by this user
7.16
4
User Access Control: Examples
User Access Control: Examples
Klaus:
GRANT Update ON Movie TO Anna;
owner
Klaus
Anna
Movie
Priv
Priv
Priv
Grant
Owner: REVOKE Update ON Movie FROM Klaus CASCADE;
owner
Klaus
Anna
Movie
Priv
7.17
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
Owner: GRANT Update ON Movie TO Klaus WITH GRANT OPTION;
User Access Control: Examples
Klaus:
GRANT Update ON Movie TO Anna;
owner
Klaus
Anna
Movie
Priv
Priv
Priv
Grant
Owner: REVOKE GRANT OPTION FOR Update ON Movie FROM
Klaus CASCADE;
owner
Anna
Klaus
Movie
Priv
Priv
7.18
User Access Control: Object owners
Owner: GRANT Update ON Movie TO Anna;
Klaus: GRANT Update ON Movie TO Anna;
owner
Klaus
Anna
Movie
Priv
Priv
Priv
Owner: REVOKE GRANT OPTION FOR Update ON Movie FROM
Klaus CASCADE;
owner
Anna
Klaus
Priv
Priv
7.19
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
Owner: GRANT Update ON Movie TO Klaus WITH GRAND OPTION;
Movie
Owner: GRANT Update ON Movie TO Klaus WITH GRANT OPTION;
Schema owner:
- Right for create, drop, alter (no privilege, not grantable)
- All privileges on schema objects
Object creator/owner:
- Create statement: current authorizationID is owner
- Enhanced SQL:1999 : owner needn't be creator
Current user privileges in Oracle:
SQL> SELECT * FROM session_privs;
PRIVILEGE
---------------------------------------CREATE SESSION
ALTER SESSION
CREATE TABLE
....
7.20
5
SQL in Programs: Introduction
SQL in Programs: Impedance Mismatch
- Sub-language for data access
- Efficient database operations
Host language:
-
Control structures
Complex computations
User interface: output formatting, forms
Transactions: DB interactions as unit of work
SQL and host language needed
7.21
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL
Impedance Mismatch:
differing data model of SQL and host language
Problems:
- Set oriented operations vs manipulation of individuals
- Interconnection of program variables and SQL statements
- Compilation time of embedded SQL-statements
7.22
SQL in Programs: 1. 4GL
1. Fourth Generation Languages (4GL)
Underlying assumption:
- Decreasing importance
2. Module Languages
- Standardized in SQL:1999
3. Call level interface
- Most important approach
- Standardized in SQL:1999
4. Component architectures
- Hiding the details of DB interaction
- Example: Enterprise Java Beans (EJB)
7.23
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Program/DBS Communication
- application programs algorithmically simple
- sophisticated output formatting needed
- difficult to switch between different DBS
Technical concept:
Client workstation
(presentation,
requests, GUI)
Database server
Proprietary protocol
Decreasing importance
7.24
6
SQL in Programs: 2. Modules (cont)
Parameterized modules of SQL statements
Standardized in SQL:1999
Compiled for a particular language
Linked to application program (statically?)
Language Examples: COBOL, C, ADA, ...
Example:
Disadvantages:
- SQL code hidden in application and vice versa
- Not widely used
Used in stored procedures (e.g., Oracle PL/SQL)
Executed under control of DBS
7.25
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: 2. Modules
MODULE demo NAMES are ascii
LANGUAGE FORTRAN
SCHEMA movie_db AUTHORIZATION ...
Returned
state value
Program
Language
variables
PROCEDURE discount_op
(SQLSTATE, :title VARCHAR(40),
:discount DECIMAL(3,2))
UPDATE Movie M
SET pricePday = pricePday - :discount
WHERE M.title = :title;
PROCEDURE customerState
(SQLSTATE, :customer INTEGER)
SELECT movie_id,tape_id,from_date
FROM Tape T, Rental R
WHERE R.member = customer
AND R.tape_id = T.id;
7.26
SQL in Programs: 3. Call level interface
Interface in standard programming languages
Proprietary library routines, API
Language/DBS specific library of procedures
Embedded C / Java / ..
Standardized language extensions
Standardized API
- Open Database connection (ODBC),
- Java Database Connectivity (JDBC)
7.27
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: 3. Call level interface
Example: MySQL C API
- Buffer for transferring commands and results
- API data types, e.g.,
MYSQL handle for db connections
MYSQL_RES result set structure
- API functions, e.g.,
mysql_real_query()
mysql_real_query(MYSQL *mysql,
const char *query,
unsigned int queryLength)
7.28
7
SQL in Programs: Embedded SQL
Direct SQL:
Program with of "native" and SQL-like statements
Pre-compiler = Preprocessor creates native code
Calls to DBS resources included
Programmer: embedded SQL or function calls
- SQL interpreter accepts and executes SQL commands
SQL in host language:
- Program in programming language (C, Java,…)
- Parts of program in SQL statements
- Most implementations: call level interface used
- Most popular: Embedded C (Oracle: PRO*C)
Java support
- SQLJ = Embedded Java
- JDBC = Standardized call interface for Java
7.29
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Embedded SQL
SQL
library
Host language
+
Embedded SQL
Preprocessor
Host language
+
Function Calls
Host language
compiler
7.30
SQL in Programs: Embedded SQL
Static embedding:
Concepts:
Dynamic SQL:
- SQL-String compiled at runtime
- variable bindings at runtime
7.31
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Static/dynamic embedding
- SQL commands known in advance
- SQL-compilation and language binding at pre-compile time
Object-code
program
- Well defined type mapping (for different languages)
- Syntax for embedded SQL statements
EXEC SQL {SELECT title FROM ...}
- Binding to host language variables
EXEC SQL
{SELECT id FROM Movie
WHERE titel = :titleString};...
- Exception handling
WHENEVER <condition> <action>
SQLSTATE
7.32
8
SQL in Programs: Embedded SQL
SQL / Host Language Interface:
Shared variable declaration
- Embedded SQL-statement:
EXEC SQL <sql statement>
- Shared variables:
:<variableName> (access in SQL)
<variableName> (access in host language)
- Exception handling:
SQLSTATE (SQL function execution status)
e.g., 00000 - no problem
02000 – answer tuple not found
7.33
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Embedded SQL
SQL in Programs: Embedded SQL
Syntax:
EXEC SQL BEGIN DECLARE SECTION;
…
EXEC SQL END DECLARE SECTION;
- Declaration in host language
- Use variable types in common
Example: EXEC SQL BEGIN DECLARE SECTION;
integer
integer
movie_number;
tape_number;
EXEC SQL END DECLARE SECTION;
7.34
SQL in Programs: Cursor concept
Important concept
- direct insert into variable
Syntax:
EXEC SQL SELECT <attributeName>
INTO :<sharedVariable>
FROM <tableNames>
WHERE <condition>
Multiple row results:
- Use of cursors on result set
7.35
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
Single row results:
Cursor:
- Name of SQL statement and
- Handle for processing the result set record by record
Defined at runtime
Opened at runtime (SQL-statement executed)
Used in most language embeddings of SQL
- e.g., ESQL-C, PL/SQL, JDBC
7.36
9
SQL in Programs: Cursor concept
No binding of result attributes to variables
Allows traversal of result set row by row
Cursor declaration:
1.
2.
3.
4.
Cursor declaration
Cursor initialisation
Fetch tuples
Close cursor
no
DECLARE
OPEN
FETCH
EMPTY?
yes
CLOSE
7.37
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Cursor concept
SQL in Programs: Cursor concept
Cursor initialisation:
EXEC SQL OPEN <cursorName>;
-
binds input variables
executes query
puts first results into communication area
positions cursor before first row of the result set
7.38
SQL in Programs: Example
EXEC SQL FETCH <cursorName>
INTO :<shared variable>;
Puts next results into communication area
Positions cursor before before next row of the result set
Assigns tuple to shared variables
Sets SQLSTATE
7.39
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
Fetch tuples:
-
EXEC SQL DECLARE <cursorName> CURSOR
FOR <query>
#include <stdio.h>
/* declare host variables */
EXEC SQL BEGIN DECLARE SECTION;
char userid[12] = "ABEL/xyz";
char movie_name[10];
int movie_number;
int tape_number;
char temp[32];
void sql_error();
EXEC SQL END DECLARE SECTION;
/* include the SQL Communication Area */
#include <sqlca.h>
7.40
10
SQL in Programs: Example
SQL in Programs: Example
main()
{ movie_number = 200;
/* handle errors */
EXEC SQL WHENEVER SQLERROR
do sql_error("Oracle error");
/* connect to Oracle */
EXEC SQL CONNECT :userid;
printf("Connected.\n");
7.41
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
/* main program */
SQL in Programs: Example
/* declare a cursor */
EXEC SQL DECLARE movie_cursor
CURSOR FOR
SELECT m.title
FROM movie m, tape t
WHERE t.id =
:tape_number
AND
t.movie_id = m.id;
/* get user data */
printf(“Tape number? ");
gets(temp);
tape_number = atoi(temp);
7.42
SQL in Programs: Example
EXEC SQL OPEN movie_cursor;
…
/* fetch and process data in a loop
exit when no more data */
EXEC SQL WHENEVER NOT FOUND DO break;
while (1){
EXEC SQL FETCH movie_cursor
INTO :movie_name; …
}
7.43
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
/* open the cursor and
identify the result set */
/* close cursor before another SQL
statement is executed */
EXEC SQL CLOSE movie_cursor;
EXEC SQL COMMIT WORK RELEASE;
exit(0);
}
7.44
11
SQL in Programs: Cursor Options
Step through set of rows and update or delete
Ordering tuples
Syntax:
EXEC SQL DECLARE <cursorName> CURSOR
FOR <query>
FOR UPDATE ON <attribute>;
… WHERE CURRENT OF <cursorName>…
Example: EXEC SQL DECLARE myCurs CURSOR
FOR SELECT id,length,title FROM Movie
FOR UPDATE ON length
EXEC SQL UPDATE Movie
SET lenght = length + 1
WHERE CURRENT OF myCurs;
7.45
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Positioned Update
- Use ORDER BY in query
Cursor motion
- SCROLL CURSOR
- Relative to current position: PRIOR/NECT/RELATIVE<nr>
e.g., FETCH <cursorName> PRIOR INTO ...
- Absolute position: first/last/ABSOLUTE<nr>
Limit effect of changes
- Performance: cursor FOR READ ONLY
- Concurrent access: INSENSITIVE CURSOR FOR …
7.46
SQL in Programs: Dynamic SQL
Example:
Statements not known at compile time
EXEC SQL DECLARE myCurs INSENSITIVE CURSOR
FOR SELECT id,length,title FROM Movie
FOR UPDATE ON length WHERE id >100;
EXEC SQL OPEN...
EXEC SQL FETCH myCurs INTO .....
UPDATE Movie SET lenght = length + 20
WHERE CURRENT OF myCurs;
Changes not visible in result set
Visible if cursor closed and reopened
7.47
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Cursor sensitivity
- Statements computed by host language
- User input of query
Tasks at run-time:
- Pass query string to SQL system
- Translate to executable statement
- Execute statement
Use ‘Prepared Statements’
7.48
12
SQL in Programs: Dynamic SQL
Step 1:
Example:
EXEC SQL PREPARE <SQLvariable>
FROM <string>
- String: SQL statement
- SQLvariable: assigned SQL statement
- Parse and prepare statement for execution
Step 2:
EXEC SQL EXECUTE <SQLvariable>
- Execute statement SQLvariable
7.49
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Dynamic SQL
void readQuery(){
EXEC SQL BEGIN DECLARE SECTION;
char *query;
EXEC SQL END DECLARE SECTION;
…
/* prompt user for query
allocate space
make :query point to query*/
…
EXEC SQL PREPARE SQLquery FROM :query;
EXEC SQL EXECUTE SQLquery;
}
7.50
SQL in Programs: SQL & Java
Multiple execution:
SQLJ
- Prepare once
- Execute many times
Single execution:
- Combination of step 1 an 2
EXEC SQL EXECUTE IMMEDIATE <string>
- Example:
…
EXEC SQL EXECUTE IMMEDIATE :query;
…
7.51
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Dynamic SQL
- Embedded SQL for Java
- Compiles to JDBC method call
- Defined and implemented by major DBS companies
(Oracle in particular)
JDBC
-
Java call-level interface (API) for SQL DBS
DB vendor independent
Supports static and dynamic SQL
Implemented by nearly all DB vendors
7.52
13
SQL in Programs: SQLJ Example
Part 0: SQLJ Embedded SQL
// Part of a SQLJ program, one method:
- Mostly reviewed and implemented
- Integrated with JDBC API
- Oracle has placed Translator source into public domain
Part 1: SQLJ Stored Procedures and UDFs
- Using Java static methods as SQL stored procedures &
functions
- Leverages JDBC API
Part 2: SQLJ Data Types
- Pure Java Classes as SQL ADTs
- Alternative to SQL:1999 Abstract Data Types
7.53
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: SQLJ
public void changeMovie(int movieid, int newTape)
{
string mtitle;
int tnumber;
#sql { SELECT m.title, count(t.id)
INTO :mtitle, :tnumber
FROM movie m, tape t
WHERE m.id = :movieid
AND m.id = t.movie_id };
if (tnumber < 3)
#sql {INSERT INTO tape VALUES
(:newTape, 'DVD', :movieid)};
}
7.54
SQL in Programs: SQL & Java
Java in Web context (2 tier architecture):
Java in Web context (3 tier architecture):
Java application
Business Logic (application)
JDBC
Proprietary protocol of DBMS
DBMS
Database Server
7.55
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: SQL & Java
Java applet or
WWW Browser
GUI
HTTP, RMI, CORBA,…
Application server
Business Logic (application)
JDBC
Proprietary protocol of DBMS
DBMS
Database Server
7.56
14
SQL in Programs: JDBC
1. Preparation
3. Set up connection database(s)
import java.sql.*;
2. Load a driver
- many vendor products
Class.forName(
"oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:
@<host>:<port>:<db>";
- url JDBC-Driver and host information
7.57
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: JDBC
SQL in Programs: JDBC
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@<host>:<port>:<db>",
<username>,<password>);
- Several connections at a time possible
4. Create statement object
Statement stmt = con.createStatement();
- Similar to channel for sending queries to database
7.58
SQL in Programs: JDBC Example
ResultSet rs = stmt.executeQuery(“<query>" );
- results in ResultSet object
6. Process results one after the other
- processed with "hidden cursor"
while (rs.next()){
for (i = 1; i <= numCols; i++){
if (i > 1) System.out.print(",");
System.out.print(rs.getString(i));
}
}
7.59
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
5. Send SQL query string
1. Preparation
#import java.io.*;
#import java.sql.*;
#import java.util.*;
...
2. Load driver
3. Connect to database
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@kuh:1521:INTROKUH";
Protocol
Sub-protocol
Oracle-spec.
Host
Port
Connection con = DriverManager.getConnection
( url, “user", “passwort");
7.60
15
SQL in Programs: JDBC Example
4. Create SQL-statement
5. execute statement
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT id, title FROM movie");
6. Process results
while (rs.next()) {
String n = rs.getInt(“id");
String n = rs.getString(“title");
System.out.println(s + ": " + n);
}
}
7.61
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
.
.
.
.
SQL in Programs: JDBC variable binding
No explicit cursor
Several methods in JDBC
- e.g., boolean next(), void close(),
<JavaType> get<JavaType>(),
boolean wasNull()
Access result data by position or by name
- By position:
String s = rs.getString(2);
- By name:
String rs.getString ("b") ;
7.62
SQL in Programs: Prepared statements
Example:
Pass input parameters
java.sql.Statement stmt = con.createStatement();
ResultSet rs1 = stmt.executeQuery
("SELECT id, title FROM movie");
while (rs1.next()) {
int mid = rs1.getInt(“id");
String mt = rs1.getString(“title");
System.out.println("ROW:" + mid + " " + mt);}
ResultSet rs2 = stmt.executeQuery
("SELECT id, movie_id FROM tape");
while (rs2.next()) {
int tid = rs2.getInt(1);
int tmid = rs2.getInt(2);
System.out.println("ROW:" + tid + " " + tmid);}
7.63
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: JDBC variable binding
Use prepared statement
java.sql.PreparedStatement prepStmt =
con.prepareStatement(<query>);
- Statement compiled
- Missing values in query: “?”
Set value:
prepStmt.setString(<position>, <value>);
7.64
16
SQL in Programs: Prepared statements
SQL in Programs: Positioned update
prepStmt.setString(1, mTitle);
ResultSet rs = prepStmt.executeQuery() ;
while (rs.next()){
int i = r.getInt(1);
// by position, no name available
System.out.println("Number of tapes for
mTitle + " is: " +i)
}
" +
7.65
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
String mTitle;
....
java.sql.PreparedStatement prepStmt =
con.prepareStatement(
"SELECT count(*)
FROM Movie m, Tape t
WHERE t.movie_id = m.id
AND m.title = ? );
Positioned update needs cursor name
Define cursor (JDBC 1)
public void setCursorName(String name)
throws SQLException
- Use for updates and deletes
Define cursor (JDBC2)
- more flexible (anonymous) cursor handling
- setCursorName not implemented in Oracle Driver
7.66
SQL in Programs: Transactions
JDBC 2.0
Transaction:
- Result set scrollable and updateable
- Example:
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.setFetchSize(25);
ResultSet rs = stmt.executeQuery(
"SELECT id, title
FROM movie");
rs.first();
rs.updateString(“title“, “xxxxx”);
rs.updateRow();
7.67
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Positioned update
- Collection of one or more database operations executed
atomically (either all operations or none )
Programmers view:
- Everything between beginning of a sequence of operations
on the database and ‘COMMIT’ or ‘ROLLBACK’
- No explicit "transaction begin" command
... OPEN MyCurs;........ ; COMMIT;
Begin of first transaction
(first SQL command in program)
End of first transaction
7.68
17
SQL in Programs: Transactions
COMMIT
Transaction manager:
- Effects on database made permanent
ROLLBACK
- Aborts transaction
- All changes in transaction undone (rolled back)
Programmers View:
- Auto-commit mode: each SQL-command is a transaction
- Various transaction isolation levels
7.69
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Transactions
- Isolate concurrent users from each other
Problems:
- Lost update: same object concurrently updated by two
users, one update lost
- Dirty read: object value changed by transaction which
aborts later
- Non-repeatable read: same object has different value
within same transaction
- Phantom tuples: non-repeatable read caused by insertions
or deletions
7.70
SQL in Programs: Isolation levels
READ UNCOMMITTED
READ COMMITTED
SET TRANSACTION
READ ONLY,
ISOLATION LEVEL READ UNCOMMITTED
-
Allows read access to uncommitted transactions
Transaction has to be read only
Lowest locking overhead
Unpleasant effects may occur
Example:
- TA1 increases the prices of some movies in DB by 5%
- TA2 scrolls through all movies, sees new prices
7.71
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Isolation levels
SET TRANSACTION
ISOLATION LEVEL READ COMMITTED
- Allows read access to committed transactions only
- Long write locks, no or short read locks
- Non-repeatable reads
Example:
TA1
Read(a)
x=x+a
TA2
Write a=a-10
commit
Read(a)
y:=y-a
Wrong balance
7.72
18
SQL in Programs: Isolation levels
REPEATABLE READ
SERIALIZABLE
SET TRANSACTION
ISOLATION LEVEL REPEATABLE READ
-
Allows read access to committed transactions only
All data isolated from concurrent writes
Read and write locks long term until end of TA
Phantom tuples may occur
7.73
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Isolation levels
SQL in Programs: Transactions and JDBC
- Allows read access to committed transactions only
- All data isolated from concurrent writes
- No phantom tuples inserted into the read set by other
transaction
- Standard default
7.74
SQL in Programs: Visibility of changes
TRANSACTION_NONE (not implemented)
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_READ_COMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
Methods:
- public void setTransactionIsolation(int
level) throws SQLExceptionpublic void
- setAutoCommit(boolean autoCommit)
- public void commit() throws SQLException
- public void rollback() throws SQLException
7.75
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
Transactional properties of connections
-
SET TRANSACTION
ISOLATION LEVEL SERIALIZABLE
ResultSet rs = stmt1.executeQuery(
"SELECT id, length FROM movie");
int i = stmt2.executeUpdate (
“DELETE FROM movie“);
rs.first();
rs.updateString(“title“, “xxxxx”);
rs.updateRow();
Scroll-insensitive result set
- no change by other result sets – even in the same TA – are
visible
- Updates in result set r visible for operations on r
- Deletes / inserts (!) in result set r not visible
Sensitive result set:
- depending on connection isolation level
7.76
19
SQL in Programs: Summary
Abort transaction when error:
Access Rights
EXEC SQL WHENEVER SQLERROR CONTINUE;
EXEC SQL ROLLBACK WORK RELEASE;
- WHENEVER SQLERROR CONTINUE prevents ROLLBACK
from (infinite) invocation of routine
Example:
void sql_error(msg){
char buf[500];
int buflen, msglen;
EXEC SQL WHENEVER SQLERROR CONTINUE;
EXEC SQL ROLLBACK WORK RELEASE;
buflen = sizeof (buf);
sqlglm(buf, &buflen, &msglen);
printf("%s\n", msg);
printf("%*.s\n", msglen, buf);
exit(1); }
7.77
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
A. Hinze, Freie Universität Berlin, SS 2002, Einführung in Datenbanken+Datenbanken für die Bioinformatik
SQL in Programs: Exception handling
- Means to ensure data security
- Privileges to roles
Program – DB communication:
-
Fourth Generation Languages (4GL)
Module Languages
Call level interface
Component architectures
Transactions in programs
- Isolation levels
- Begin, end transaction
7.78
20