Download 5. SQL Ch5

Document related concepts

Concurrency control wikipedia , lookup

DBase wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft Access wikipedia , lookup

Tandem Computers wikipedia , lookup

Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Ingres (database) wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Relational algebra wikipedia , lookup

Clusterpoint wikipedia , lookup

Null (SQL) wikipedia , lookup

Database model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Relational model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
5
Chapter 5
Structured Query Language
(SQL)
Hachim Haddouti
5
In this chapter, you will learn:
• Basic commands and functions of SQL
• SQL for data manipulation (DML)
• How to use SQL to query a database to extract
useful information
• How SQL is used for data administration (to
create tables, indexes, and views) DDL
• Advanced SQL features such as views, stored
procedures, and triggers
Hachim Haddouti and Rob & Coronel, Ch5
2
5
Introduction to SQL
• Ideal database language
– Create database and table structures
– Perform basic data management chores (add,
delete, and modify)
– Perform complex queries to transform data into
useful information
• SQL is the ideal DB language
– Data definition language
– Data manipulation language
– Non-procedural language (only what and not how)
Hachim Haddouti and Rob & Coronel, Ch5
3
5
Good Reasons to Study SQL
• ANSI standardization effort led to de facto query standard
for relational database
• Forms basis for present and future DBMS integration
efforts
• Becomes catalyst in development of distributed databases
and database client/server architecture
• Note:
– SQL: as successor of the prototype language SEQUEL
(IBM Almaden Research Center San Jose, around 1975).
– 2 knowm version of SQL (SQL2 also called SQL-92, and
SQL99 or SQL 3).
– For a complete pecification of SQL see [ Melton93].
About 700 pages or www.ansi.org or A Guide to the
SQL Standard [DATE97].
– But, some dialects (difference is minor)
Hachim Haddouti and Rob & Coronel, Ch5
4
5
Data Definition Commands
• Create database structure
– Holds all tables and is a collection of physical files
stored on disk
– DBMS automatically creates tables to store metadata
– Database administrator creates structure or schema
• Logical group of tables or logical database
• Groups tables by owner
• Enforces security
Hachim Haddouti and Rob & Coronel, Ch5
5
5
Creating Table Structure
• Used to describe layout of a table
• Tables store end-user data
• May be based on data dictionary entries
• Typical restrictions placed by DBMS
– Names cannot exceed 18 characters
– Names must start with a letter
– Names can contain only letters, numbers, and underscores
(_)
– Names cannot contain spaces
Hachim Haddouti and Rob & Coronel, Ch5
6
5
Typical Data Types
• INTEGER
– Numbers without a decimal point
• SMALLINT
– Uses less space than INTEGER (up to 6 digits)
• DECIMAL(p,q)
– P number of digits; q number of decimal places
• CHAR(n)
– Character string n places long (fixed length)
• VARCHAR(n)
– Variable Length string up to n characters long
• DATE
– Dates in DD-MON-YYYY or MM/DD/YYYY
Hachim Haddouti and Rob & Coronel, Ch5
7
5
Creating Table Structure cont.
CREATE TABLE <table name>
(<attribute1 name and attribute1 characteristics,
attribute2 name and attribute2 characteristics,
attribute3 name and attribute3 characteristics,
primary key designation,
foreign key designation and foreign key requirement>);
CREATE TABLE CUSTOMER
(customer_ID INTEGER NOT NULL UNIQUE,
customer_name char(25) NOT NULL,
PRIMARY KEY (customer_id));
Hachim Haddouti and Rob & Coronel, Ch5
8
5
Creating Table Structure cont.
CREATE TABLE EMPLOYEE (
EMP_NUM
EMP_LNAME
EMP_FNAME
EMP_INITIAL
EMP_HIREDATE
JOB_CODE
CHAR(3)
NOT NULL,
CHAR(15)
NOT NULL,
CHAR(15)
NOT NULL,
CHAR(1),
DATE
NOT NULL,
CHAR(3),
PRIMARY KEY (EMP_NUM),
FOREIGN KEY (JOB_CODE) REFERENCES JOB);
Note: Composite key!
Hachim Haddouti and Rob & Coronel, Ch5
9
5
Using Domains
• Domain is set of permissible values for a column
• Definition requires:
–
–
–
–
Name
SQL common Data type
Default value
Domain constraint or condition
CREATE DOMAIN <domain_name> AS DATA_TYPE
[DEFAULT <default_value>]
[CHECK (<condition>)]
CREATE DOMAIN WEEK AS VARCHAR(15)
CHECK ( VALUE IN (‘Monday’, ‘Tuesday’, … ‘Sunday’));
Note: in Oracle 8i use CREATE TYPE
Hachim Haddouti and Rob & Coronel, Ch5
10
5
SQL Integrity Constraints
• Adherence to entity integrity and referential
integrity rules is crucial
– Entity integrity enforced automatically if primary
key specified in CREATE TABLE command
sequence
CREATE TABLE EMPLOYEE
(EMP_NUM CHAR(25) NOT NULL UNIQUE,
...,
PRIMARY KEY (EMP_NUM));
– Referential integrity can be enforced in
specification of FOREIGN KEY
CREATE TABLE link
( ...,
JOBCODE Integer NOT NULL,
FOREIGN KEY (JOBCODE) REFERENCES table2);
Hachim Haddouti and Rob & Coronel, Ch5
11
5
Data Manipulation Commands
Common SQL Commands
Hachim Haddouti and Rob & Coronel, Ch5
12
5
Data Entry and Saving
• Enters data into a table
INSERT INTO <table name>
VALUES (attribute 1 value, attribute 2 value, … etc.);
• Saves changes to disk
COMMIT <table names> ;
Hachim Haddouti and Rob & Coronel, Ch5
13
5
Data Entry and Saving cont.
INSERT INTO EMPLOYEE
VALUES ('101', 'News', 'John', 'G', '11/8/94', '502');
INSERT INTO EMPLOYEE
VALUES ('102', 'Senior', 'David', 'H', '7/12/87', '501');
Hachim Haddouti and Rob & Coronel, Ch5
14
5
Result of Create and Insert
EMP_NUM
EMP_LNAME
EMP_FNAME
EMP_INITIAL
EMP_HIREDA
TE
JOB_CODE
101
News
John
G
08-Nov-94
502
102
Senior
David
H
12-Jul-87
501
After many Inserts:
Hachim Haddouti and Rob & Coronel, Ch5
15
5
Listing Table Contents and Other
Commands
• Allows table contents to be listed
SELECT <attribute names> FROM <table names>;
• UPDATE command makes data entry corrections
• ROLLBACK command restores database back to
previous condition if COMMIT hasn’t been used
(undoes all updates performed by the
transaction)
• DELETE command removes table row
Hachim Haddouti and Rob & Coronel, Ch5
16
5
Motivating example: Rollback
– Transfer of money from one account to
another involves two steps:
•
deduct from one account and credit to another
– If one steps succeeds and the other fails,
database is in an inconsistent state
– Therefore, either both steps should
succeed or neither should
• If any step of a transaction fails, all work done by the
transaction can be undone by rollback work.
• Rollback of incomplete transactions is done automatically,
in caseHachim
of system
Haddouti and failures
Rob & Coronel, Ch5
17
5
Queries
• Creating partial listings of table contents
SELECT <column(s)>
FROM <table name>
WHERE <conditions>;
Mathematical Operators
Hachim Haddouti and Rob & Coronel, Ch5
18
5
Examples
• Mathematical operators
SELECT EMP_LNAME, EMP_FNAME, EMP_NUM, JOB_CODE
FROM EMPLOYEE
WHERE JOB_CODE = 500;
• Mathematical operators on character attributes
SELECT EMP_LNAME, EMP_FNAME, EMP_NUM, EMP_INITIAL
FROM EMPLOYEE
WHERE EMP_INITIAL 500 > ‘G’;
• Mathematical operators on dates
SELECT EMP_LNAME, EMP_FNAME, EMP_NUM, EMP_HIREDATE
FROM EMPLOYEE
WHERE EMP_HIREDATE >= ‘01/20/2002’;
Hachim Haddouti and Rob & Coronel, Ch5
19
5
Computed Columns
• New columns can be created through valid
computations or formulas
– Formulas may contain mathematical operators
– May contain attributes of any tables specified in
FROM clause
• Alias is alternate name given to table or column
in SQL statement
SELECT P_DESCRIPT,P_ONHAND,P_PRICE,P_ONHAND*P_PRICE
AS TOTVALUE
FROM PRODUCT;
Hachim Haddouti and Rob & Coronel, Ch5
20
5
Operators
• Logical: AND, OR, NOT
SELECT *
FROM PRODUCT
WHERE V_CODE = 21344 OR V_CODE = 24288;
• Rules of precedence
– Conditions within parenthesis executed first
– Boolean algebra
• Special
–
–
–
–
–
BETWEEN - defines limits
IS NULL - checks for nulls
LIKE - checks for similar string
IN - checks for value in a set
EXISTS - opposite of IS NULL
Hachim Haddouti and Rob & Coronel, Ch5
21
5
Examples of Special Operators
•
SELECT * FROM PRODUCT
WHERE P_PRICE BETWEEN 50.000 AND 100.000;
•
SELECT P_CODE, P_DESCRIPT FROM PRODUCT
WHERE P_MIN IS NULL
•
SELECT EMP_LNAME FROM EMPLOYEE
WHERE EMP_LNAME LIKE ‘S%’
•
SELECT EMP_LNAME FROM EMPLOYEE
WHERE EMP_LNAME LIKE ‘Ha_him’
•
SELECT EMP_LNAME FROM EMPLOYEE
WHERE EMP_LNAME NOT LIKE ‘Ha_him’
•
SELECT EMP_LNAME FROM EMPLOYEE
WHERE UPPER(EMP_LNAME) LIKE ‘HA_HIM’
•
Note: some other RDBMS use * and ? Instead of % and _
Hachim Haddouti and Rob & Coronel, Ch5
22
5
Advanced Data Management
Commands
• ALTER - changes table structure
• ADD - adds column
• MODIFY - changes column characteristics
ALTER TABLE <table name>
ADD (<column name> <new column characteristics>);
ALTER TABLE <table name>
MODIFY (<column name> <new column characteristics>);
ALTER TABLE Employee
MODIFY (Emp_Lname CHAR (35)); /* this will work only
in the case that the column is empty*/
NOTE: Be careful by including NOT NULL clause in add a new column
Hachim Haddouti and Rob & Coronel, Ch5
23
5
Advanced Data Management
Commands cont.
•Entering data into new column
UPDATE PRODUCT
SET P_SALECODE = ‘2’
WHERE P_CODE = ‘1546-QQ2’;
• Deleting Table Rows
DELETE FROM EMPLOYEE
WHERE EMP_NUM = ‘102’;
Hachim Haddouti and Rob & Coronel, Ch5
24
5
Query Example
• Assume: account (account-number, branchname, balance)
• Increase all accounts with balances over $10,000
by 6%, all other accounts receive 5%.
–Write two update statements:
•update account
set balance = balance  1.06
where balance > 10000
•update account
set balance = balance  1.05
where balance  10000
Hachim Haddouti and Rob & Coronel, Ch5
25
5
Advanced Data Management
Commands (con’t.)
• Dropping a column
ALTER TABLE VENDOR
DROP COLUMN V_ORDER;
• Arithmetic operators and rules of precedence
Hachim Haddouti and Rob & Coronel, Ch5
26
5
Advanced Data Management
Commands (con’t.)
• Copying parts of tables
INSERT INTO <receiving table> <receiving table’s column names>
SELECT <column names of the columns to be copied>
FROM <contributing table name>;
• Deleting a table from database
• DROP TABLE PART;
• Primary and foreign key designation
ALTER TABLE LINE
ADD PRIMARY KEY (INV_NUMBER, LINE_NUMBER)
ADD FOREIGN KEY (INV_NUMBER) REFERENCES INVOICE
ADD FOREIGN KEY (PROD_CODE) REFERENCES PRODUCT;
Hachim Haddouti and Rob & Coronel, Ch5
27
5
More Complex Queries and SQL
Functions
• Ordering a listing ( always last in command
sequence)
ORDER BY <attributes>
• Results ascending by default
– Descending order uses DESC
ORDER BY <attributes> DESC
• Cascading order sequence
ORDER BY <attribute 1, attribute 2, ...>
Hachim Haddouti and Rob & Coronel, Ch5
28
5
More Complex Queries and SQL
Functions (con’t.)
• Listing unique values
– DISTINCT clause produces list of different values
SELECT DISTINCT V_CODE
FROM PRODUCT;
• Aggregate functions
– Mathematical summaries
Num of non-null rows in a given column
Min attribute value
Max attribute value
Sum of of all selected attribute values
Arithmetic average for the give column
Hachim Haddouti and Rob & Coronel, Ch5
29
5
• COUNT
Example Aggregate
Function Operations
SELECT COUNT(DISTINCT V_CODE)
FROM PRODUCT;
SELECT COUNT(DISTINCT V_CODE)
FROM PRODUCT
WHERE P_PRICE <= 10.00;
• MAX and MIN
SELECT MIN(P_PRICE)
FROM PRODUCT;
SELECT P_CODE, P_DESCRIPT, P_PRICE
FROM PRODUCT
WHERE P_PRICE = MAX(P_PRICE);
Hachim Haddouti and Rob & Coronel, Ch5
30
5
Example Aggregate
Function Operations (con’t.)
• SUM
SELECT SUM(P_ONHAND * P_PRICE)
FROM PRODUCT;
• AVG
SELECT P_DESCRIPT, P_ONHAND, P_PRICE, V_CODE
FROM PRODUCT
WHERE P_PRICE >
(SELECT AVG(P_PRICE) FROM PRODUCT)
ORDER BY P_PRICE DESC;
NOTE: Except COUNT, all aggregations apply to a single attribute
(eg. SELECT Count(*) FROM Purchase)
Hachim Haddouti and Rob & Coronel, Ch5
31
5
Example Query
• Assume: account (account-number, branchname, balance)
• Delete the record of all accounts with balances
below the average at the bank.
delete from account
where balance < (select avg (balance)
from account)
Hachim Haddouti and Rob & Coronel, Ch5
32
5
More Complex Queries and
SQL Functions (con’t.)
• Grouping data
– Creates frequency distributions
– Only valid when used with SQL arithmetic functions
SELECT P_SALECODE, MIN(P_PRICE)
FROM PRODUCT_2
GROUP BY P_SALECODE;
– HAVING clause operates like WHERE for grouping
output , not to columns
SELECT V_CODE,COUNT(DISTINCT(P_CODE)),AVG(P_PRICE)
FROM PRODUCT_2
GROUP BY V_CODE
HAVING AVG(P_PRICE) < 10;
Hachim Haddouti and Rob & Coronel, Ch5
33
5
Query Example
Assume the following table:
Student (SID, Std_Name, STD_Address, STD_GPA)
Is the following SQL statement correct?
SELECT Std_Name, STD_GPA
FROM Student
GROUP BY STD_GPA;
And this? COUNTS HOW MANY PRODCUT EACH VENDOR PROVIDES
SELECT V_CODE, COUNT(DISTINCT P_CODE)
FROM PRODUCT
GROUP BY V_CODE;
Hachim Haddouti and Rob & Coronel, Ch5
34
5
Query Example cont.
Find the names of all students where the average GPA
is more than 3.0.
select Std_Name, avg (Std_GPA)
from Student
group by Std_Name
having avg (Std_GPA) > 3
Hachim Haddouti and Rob & Coronel, Ch5
35
5
More Complex Queries and
SQL Functions (con’t.)
• Virtual tables: creating a view
– CREATE VIEW command
– Creates logical table existing only in virtual memory
– Once a view is defined, the view name can be used to refer to
the virtual relation that the view generates.
CREATE VIEW PRODUCT_3 AS
SELECT P_DESCRIPT, P_ONHAND, P_PRICE
FROM PRODUCT
WHERE P_PRICE > 50.00;
– SQL indexes
CREATE INDEX P_CODEX
ON PRODUCT(P_CODE);
Hachim Haddouti and Rob & Coronel, Ch5
36
5
More Complex Queries and
SQL Functions (con’t.)
• Joining database tables
– Data are retrieved from more than one table
SELECT PRODUCT.P_DESCRIPT, PRODUCT.P_PRICE,
VENDOR.V_NAME, VENDOR.V_CONTACT,
VENDOR.V_AREACODE, VENDOR.V_PHONE
FROM PRODUCT, VENDOR
WHERE PRODUCT.V_CODE = VENDOR.V_CODE;
– Recursive queries joins a table to itself (List of all
employees with their manager’s name?)
SELECT A.EMP_NUM,A.EMP_LNAME,A.EMP_MGR,
B.EMP_LNAME FROM EMP A, EMP B
WHERE A.EMP_MGR=B.EMP_NUM
ORDER BY A.EMP_MGR
Hachim Haddouti and Rob & Coronel, Ch5
37
5
Query Example
Relation loan
Loan_number
Branch_name
Relation borrower
amount
Customer_name Loan_number
L-170
Downtown
3000
Jones
L-170
L-230
Redwood
4000
Smith
L-230
L-260
Perryridge
1700
Hayes
L-155
SELECT * FROM loan L, borrower B
WHERE L.loan_number = B.loan_number
Loan_number
Branch_name
amount
Customer_name Loan_number
L-170
Downtown
3000
Jones
L-170
L-230
Redwood
4000
Smith
L-230
Hachim Haddouti and Rob & Coronel, Ch5
38
5
Nested Subqueries
• SQL provides a mechanism for the nesting of
subqueries.
• A subquery is a select-from-where expression that
is nested within another query.
• A common use of subqueries is to perform tests
for set membership, set comparisons, and set
cardinality.
Hachim Haddouti and Rob & Coronel, Ch5
39
5
Query Example
• Find all customers who have both an account and
a loan at the bank.
select distinct customer-name
from borrower
where customer-name in (select customer-name
from depositor)
• Find all customers who have a loan at the bank but do not
have an account at the bank
select distinct customer-name
from borrower
where customer-name not in (select customer-name
from depositor)
Hachim Haddouti and Rob & Coronel, Ch5
40
5
Updatable Views
• Common operation in production environments is
use of batch routines to update master table
attributes using transaction data
• Overnight batch jobs
• Not all views are updatable
• Restrictions
– GROUP BY expressions cannot be used
– Cannot use set operators---UNION,
INTERSECTION, etc.
– Most restrictions based on use of JOINS or group
operators in views
Hachim Haddouti and Rob & Coronel, Ch5
41
Procedural SQL
5
• SQL shortcomings
– Doesn’t support execution of stored procedures based on
logical condition (IF THEN, DO WHILE)
– Fails to support looping operations
• Solutions
– Embedded SQL can be called from within procedural
programming languages
– Shared Code is isolated and used by all application programs.
– Procedural SQL (PL/SQL) stored within the database,
executed by DBMS, and invoked by the end user
• Triggers
• Stored procedures
• PL/SQL functions (Oracle)
Hachim Haddouti and Rob & Coronel, Ch5
42
5
Procedural SQL (con’t.)
• Procedural SQL allows the use of procedural code and SQL
statements that are stored within the database.
• The procedural code is executed by the DBMS when it is
invoked by the end user.
• End users can use procedural SQL (PL/SQL) to create:
– Triggers
– Stored procedures
– PL/SQL functions
• SQL provides a module language
– permits definition of procedures in SQL, with if-thenelse statements, for and while loops, etc
Hachim Haddouti and Rob & Coronel, Ch5
43
5
Triggers
• Procedural SQL code invoked before or after
data row is selected, inserted, or updated
• Associated with a database table
• Table may have multiple triggers
• Executed as part of transaction
• Can enforce particular constraints
• Automate critical actions and provide warnings
for remedial action
• Can update values, insert records, and call
procedures
• Add processing power
Hachim Haddouti and Rob & Coronel, Ch5
44
5
Triggers (con’t.)
• An example (for oracle)
CREATE OR REPLACE TRIGGER <trigger_name>
[BEFORE/AFTER]
[DELETE/INSERT/UPDATE OF <column_name]
ON <table_name>
[FOR EACH ROW]
BEGIN
PL/SQL instructions;
……………
END;
See a concret example on page 270;
Hachim Haddouti and Rob & Coronel, Ch5
45
5
Stored Procedures
• Named collection of procedural and SQL statements
stored in database e.g. to represent multiple update
transactions
• Transmitted and executed as entire  reduces network
traffic and improve performance
• permit external applications to operate on the database
without knowing about internal details
• Invoked by name
Hachim Haddouti and Rob & Coronel, Ch5
46
5
Stored Procedures
• Executed as unit
CREATE OR REPLACE PROCEDURE procedure_name
(argument IN/OUT data-type, etc)
IS/AS BEGIN
DECLARE variable name and data type
PL/SQL or SQL statements;
END;
• Invoked with EXEC or call
EXEC store_procedure_name
(parameter, parameter, …)
Hachim Haddouti and Rob & Coronel, Ch5
47
5
Embedded SQL,
see also procedural SQL
• The SQL standard defines embeddings of SQL in a variety
of programming languages such as Cobol, Pascal, Fortran,
C, and Java.
• 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.
• EXEC SQL statement is used to identify embedded SQL
request to the preprocessor
EXEC SQL <embedded SQL statement > END-EXEC
Note: this varies by language. E.g. the Java embedding
uses
# SQL {<embedded SQL statement > } ;
Hachim Haddouti and Rob & Coronel, Ch5
48
5
Example Query
From within a host language, find the names and cities of
customers with more than the variable amount dollars in some
account.
• Specify the query in SQL and declare a cursor for it
EXEC SQL
declare c cursor for
select customer-name, customer-city
from depositor D, customer C, account A
where D.customer_name = C.customer_name
and D.account_number = A.account_number
and account.balance > :amount
END-EXEC
Hachim Haddouti and Rob & Coronel, Ch5
49
5
Embedded SQL (Cont.)
• The open statement causes the query to be evaluated
EXEC SQL open c END-EXEC
• 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
• 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. E.g. the Java
embedding defines Java iterators to step through result
tuples.
Hachim Haddouti and Rob & Coronel, Ch5
50
5
Dynamic SQL
• Allows programs to construct and submit SQL queries at
run time (programs can create SQL queries qt run time).
• Example of the use of dynamic SQL from within a C
program. In contrast to embedded SQL,
SQL statements are precompiled.
•
char *
sqlprog = “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 a place
holder for a value that is provided when the SQL program is
executed.
Hachim Haddouti and Rob & Coronel, Ch5
51
5
ODBC
• Open DataBase Connectivity(ODBC) standard
– standard for application program to communicate
with a database server.
– Initiated by Microsoft
– application program interface (API) to
• open a connection with a database,
• send queries and updates,
• get back results.
• Applications such as GUI, spreadsheets, etc. can
use ODBC
Hachim Haddouti and Rob & Coronel, Ch5
52
5
ODBC (Cont.)
•
•
•
•
•
Each database system supporting ODBC provides a "driver"
library that must be linked with the client program.
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.
ODBC program first allocates an SQL environment, then a
database connection handle.
Opens database connection using SQLConnect(). Parameters for
SQLConnect:
– connection handle,
– the server to which to connect
– the user identifier,
– password
Must also specify types of arguments:
– SQL_NTS denotes previous argument is a null-terminated
string.
Hachim Haddouti and Rob & Coronel, Ch5
53
5
ODBC Code
• 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);
}
Hachim Haddouti and Rob & Coronel, Ch5
54
5
JDBC
• JDBC is a Java API for communicating with database
systems supporting SQL, initiated by SUN
• JDBC supports a variety of features for querying and
updating data, and for retrieving query results
• JDBC also supports metadata retrieval, such as querying
about relations present in the database and the names and
types of relation attributes
• 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
Hachim Haddouti and Rob & Coronel, Ch5
55
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:@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);
}
}
Hachim Haddouti and Rob & Coronel, Ch5
56
5
JDBC Code (Cont.)
• 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);
}
• 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));
}
Hachim Haddouti and Rob & Coronel, Ch5
57
5
JDBC Code Details
• Getting result fields:
– rs.getString(“branchname”) and rs.getString(1)
equivalent if branchname is the first argument of
select result.
• Dealing with Null values
int a = rs.getInt(“a”);
if (rs.wasNull()) Systems.out.println(“Got null value”);
Hachim Haddouti and Rob & Coronel, Ch5
58
5
Review: Link correctly
•
•
SELECT *
FROM Company
WHERE
country=“Maroc” AND
stockPrice > 50
SELECT name, stock price
FROM Company
WHERE
country=“Maroc” AND
stockPrice > 50
Hachim Haddouti and Rob & Coronel, Ch5
• Selections
• Projection
59
5
Review: Resulting Table?
•
SELECT name AS company, stockprice AS price
FROM Company
WHERE country=“Maroc” AND stockPrice > 50
Hachim Haddouti and Rob & Coronel, Ch5
60
5
Procedural or non-procedural?
Open Table
Go to row where Name = „Franz“ (using index)
If found:
While:
Print
Read table rows in a seauence by using the index Name
At the end of Table leave While
While end
....
Hachim Haddouti and Rob & Coronel, Ch5
61