2. 2
This lesson is NOT for absolute beginners
Target audience:
Familiar with databases (MySQL / SQL Server / other)
Know what is table / column / relationship
Know what is SQL and simple SQL commands
Have basic coding skills (C# / Java / JS / other)
Target Audience
3. Table of Contents
1. Oracle Database Overview
2. Installing Oracle Database 12c
3. Installing SQL Developer
4. Creating DB Schemas and Tables
5. SQL Language Basics
SELECT, INSERT, UPDATE, DELETE, …
6. PL/SQL: Procedures, Functions, Triggers
7. Accessing Oracle from C# and Java
3
5. 5
Oracle Database
World's leader in enterprise database systems
Powers big organizations, e.g. the financial sector
Designed for very large databases (exabytes of data)
Supports everything from the DB world
Transactions, stored procedures, big data, cloud, …
Very expensive, for big players only
Has a free Expression Edition – Oracle 11g XE
What is Oracle Database?
8. 8
Installing Oracle 12c – Use a Built-In User
Developers may use
"Windows Built-in Account"
for simplified setup
9. 9
Installing Oracle 12c – Location & Password
Select a directory
without spaces,
e.g. C:oracle
Don't select "Container
database". It is too complex!
15. 15
Oracle SQL Developer is free GUI tool for managing Oracle databases:
SQL queries, edit table data, edit DB schema, write code, debug, …
Oracle SQL Developer
Oracle 12c Enterprise comes with
pre-installed SQL Developer 3.2
(old version, not recommended)
16. 16
1. Download Oracle SQL Developer 4.1 from
http://oracle.com/technetwork/developer-tools/sql-developer
2. Extract the ZIP archive in some folder, e.g.
C:oraclesqldeveloper
3. Run sqldeveloper.exe
4. Choose your JDK location
5. Create a start menu shortcut
6. Enjoy
Installing Oracle SQL Developer
19. 19
User SYS
Holds the system schema SYS and data dictionary (DB metadata)
Has a DBA role
Includes most database system privileges, e.g. "create user"
Has a SYSDBA privilege – can start / stop / create / recover DB
User SYSTEM
Has a DBA role – can administer the DB, e.g. create / drop users
No SYSDBA privilege
Users SYS and SYSTEM in Oracle DB
25. 25
Oracle runs single database with multiple users
MS SQL Server and MySQL have many databases
"User (schema) in Oracle" == "Database" in MSSQL and MySQL
Creating a new user (schema) and give typical privileges:
Creating a New User (Schema) in Oracle
CREATE USER maria IDENTIFIED BY "password123";
GRANT CREATE SESSION, CREATE TABLE, CREATE VIEW,
CREATE PROCEDURE, CREATE SEQUENCE, CREATE TRIGGER,
UNLIMITED TABLESPACE TO maria;
26. 26
Users in Oracle may have certain privileges
CREATE SESSION – allows the users to connect to DB
CREATE TABLE / CREATE VIEW / CREATE PROCEDURE / …
UNLIMITED TABLESPACE – unlimited storage quota (0 by default)
SYSDBA – start / stop / edit / backup the entire database
Users in Oracle may have certain roles
DBA – database administrator (full DB access)
CONNECT + RESOURCE – login + create / edit tables and DB objects
User Privileges and Roles in Oracle
27. 27
Creating a New User in SQL Developer
Granting "DBA" role
is easy but might be
a security risk
29. 29
NUMBER(precision, scale) – a number, e.g. 12345
precision – total number of digits
scale – number of digits to the right of the decimal point
VARCHAR2(length) – sequence of characters (up to 4000)
NVARCHAR2(length) – sequence of Unicode characters
DATE – date and time, e.g. "18-June-2015 20:30:07"
BLOB – binary large object (e.g. PDF document or JPEG image)
CLOB – character large object (e.g. HTML document)
Oracle Data Types
30. 30
Oracle database has some specifics
One database with many users (schemas)
Each user has its own schema (tables and other DB objects)
Use UPPERCASE for all identifiers
Otherwise you should use the quoted syntax, e.g. "My Table"
No auto-increment columns until version 12c
Use a SEQUENCE + TRIGGER for auto-increment in Oracle 11g / 10g
In Oracle NULL is the same like "" (empty string)
This causes many problems!
Beware: Oracle has Specifics!
37. Creating DB Schema "Maria" Holding
Countries and Towns (One to Many)
Live Exercise in Class (Lab)
38. SQL Language – Basics
Basics SQL Commands: SELECT, INSERT,
UPDATE, DELETE, CREATE, ALTER, DROP
SELECT *
FROM COUNTRIES
WHERE COUNTRY_ID = 'UK'
SELECT
c.COUNTRY_NAME AS COUNTRY,
r.REGION_NAME AS REGION
FROM COUNTRIES c
JOIN REGIONS r ON
c.REGION_ID = r.REGION_ID
39. 39
SELECT
WHERE (filtering)
JOIN (joining tables)
GROUP BY (grouping)
INSERT
UPDATE
DELETE
SQL Language
SELECT
d.DEPARTMENT_NAME AS DEPT,
COUNT(e.EMPLOYEE_ID) AS EMP_COUNT
FROM
DEPARTMENTS d JOIN EMPLOYEES e ON
e.DEPARTMENT_ID = d.DEPARTMENT_ID
GROUP BY
d.DEPARTMENT_ID, d.DEPARTMENT_NAME
HAVING
COUNT(e.EMPLOYEE_ID) >= 5
ORDER BY
EMP_COUNT DESC
40. 40
In Oracle, we have the "HR" schema, coming as example
The "HR" schema holds:
Employees
Jobs
Departments
Locations (addresses)
Countries
To use it, unlock the "HR" user and change its password
The HR Sample Schema
41. 41
SELECT
WHERE
ORDER BY
SQL: SELECT, WHERE, ORDER BY
SELECT * FROM COUNTRIES
SELECT COUNTRY_ID, REGION_ID
FROM COUNTRIES
SELECT * FROM COUNTRIES
WHERE COUNTRY_ID = 'UK'
SELECT * FROM COUNTRIES
WHERE COUNTRY_ID LIKE 'C%'
OR COUNTRY_NAME LIKE 'Un%'
SELECT * FROM COUNTRIES
ORDER BY COUNTRY_NAME
SELECT * FROM COUNTRIES
ORDER BY COUNTRY_ID DESC
FETCH NEXT 3 ROWS ONLY
42. 42
Join COUNTRIES with REGIONS tables in SQL SELECT
SQL: Join Tables
SELECT *
FROM COUNTRIES JOIN REGIONS
ON COUNTRIES.REGION_ID =
REGIONS.REGION_ID
SELECT c.COUNTRY_NAME AS COUNTRY,
r.REGION_NAME AS REGION
FROM COUNTRIES c JOIN REGIONS r
ON c.REGION_ID = r.REGION_ID
43. 43
Insert a new department
SQL: INSERT
INSERT INTO DEPARTMENTS(
DEPARTMENT_ID,
DEPARTMENT_NAME,
LOCATION_ID)
VALUES (
DEPARTMENTS_SEQ.nextval,
'Brazil Sales',
2800 /* Sao Paulo, Brazil */)
Primary key is
populated by a
SEQUENCE
44. 44
Update existing department change name + commit
Update existing employee change hire date + rollback
SQL: UPDATE
UPDATE EMPLOYEES SET HIRE_DATE = '2-Jan-2001'
WHERE EXTRACT(YEAR FROM HIRE_DATE) = 2001;
ROLLBACK; -- Discard (cancel) pending changes
UPDATE DEPARTMENTS
SET DEPARTMENT_NAME = 'Brazil Sales and Marketing'
WHERE DEPARTMENT_NAME = 'Brazil Sales'
COMMIT; -- Save pending changes
45. 45
Delete existing department + commit
Delete all locations in Italy + rollback
SQL: DELETE
DELETE FROM DEPARTMENTS
WHERE DEPARTMENT_ID = 320;
COMMIT; -- Save pending changes
DELETE FROM LOCATIONS
WHERE COUNTRY_ID =
(SELECT COUNTRY_ID FROM COUNTRIES
WHERE COUNTRY_NAME = 'Italy');
ROLLBACK; -- Discard (cancel) pending changes
46. SQL Commands
Live Exercise (Lab)
1. Write SQL SELECT to find all locations in towns starting with 'S'.
2. Write SQL INSERT to create a new job (id 'SW_DEV', title 'Software
Developer', salary range 10000 … 50000).
3. Write SQL UPDATE to change the job title 'Software Developer' to
'Software Engineer' and max salary to 75000.
4. Write SQL DELETE to remove the job title 'Software Engineer'.
5. Write a SQL SELECT to find all job titles and the number of
employees for each job title. Use GROUP BY JOB_ID.
More exercises: http://www.srikanthtechnologies.com/oracle/dec9/hrqueries.html
48. 48
PL/SQL extends the SQL language in Oracle DB
Blocks (declare / begin / exception / end)
Variables, types, assignments
Conditional statements (if-then-else)
Loops (for, while, do…while)
Cursors (loops over query results)
Exceptions handling
Stored procedures, functions, triggers, packages
PL/SQL Overview
49. 49
PL/SQL – Example
SET SERVEROUTPUT ON
DECLARE
e_id EMPLOYEES.EMPLOYEE_ID%TYPE;
e_fname EMPLOYEES.FIRST_NAME%TYPE;
e_lname EMPLOYEES.LAST_NAME%TYPE;
CURSOR e_employees IS
SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME
FROM EMPLOYEES;
result CLOB;
BEGIN
result := NULL;
OPEN e_employees;
Goal of this PL/SQL program:
Collect the employee data into a
single string (comma separated)
50. 50
PL/SQL – Example (2)
LOOP
FETCH e_employees INTO e_id, e_fname, e_lname;
EXIT WHEN e_employees%NOTFOUND;
IF result IS NOT NULL THEN
result := result || ', ';
END IF;
result := result || e_id || ' (' ||
e_fname || ' ' || e_lname || ')';
END LOOP;
CLOSE e_employees;
DBMS_OUTPUT.PUT_LINE(result);
END;
51. 51
PL/SQL: Interchange Salaries – Example
CREATE OR REPLACE PROCEDURE exchange_salaries(
emp1_id NUMBER, emp2_id NUMBER)
IS
old_emp1_salary EMPLOYEES.SALARY%TYPE;
BEGIN
SELECT SALARY INTO old_emp1_salary
FROM EMPLOYEES WHERE EMPLOYEE_ID = emp1_id;
UPDATE EMPLOYEES SET SALARY =
(SELECT SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID = emp2_id)
WHERE employee_id = emp1_id;
UPDATE EMPLOYEES SET SALARY = old_emp1_salary
WHERE EMPLOYEE_ID = emp2_id;
COMMIT;
END; CALL exchange_salaries(204, 206);
52. Accessing Oracle DB from Java
Using the Oracle JDBC Driver
Connection
Statement
ResultSet
Oracle DB
setInt(…)
setDate(…)
setString(…)
54. 54
Reference the Oracle JDBC Drivers Library
<repositories>
<!-- Repository for ORACLE ojdbc7 (unofficial) -->
<repository> <id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
</dependencies>
pom.xml
Add an unofficial Maven repository
holding the Oracle JDBC drivers
Reference the latest OJDBC
library (12.1 for Java 7+)
55. 55
List All Employees from the HR Schema
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
try (Connection dbConnection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "hr", "hr")) {
Statement stmp = dbConnection.createStatement();
ResultSet rs = stmp.executeQuery("SELECT * FROM EMPLOYEES");
while (rs.next()) {
int id = rs.getInt("EMPLOYEE_ID");
String firstName = rs.getString("FIRST_NAME");
String lastName = rs.getString("LAST_NAME");
System.out.println(id + ": " + firstName + " " + lastName);
}
}
}
56. Accessing Oracle DB from C#
Using the Oracle Data Provider for .NET
OracleConnection
OracleCommand
OracleDataReader
Oracle DB
OracleParameter
OracleParameter
OracleParameter
58. 58
Configure the Data Source in App.config
<oracle.manageddataaccess.client>
<version number="*">
<dataSource alias="orcl" descriptor=
"(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)
(HOST=localhost)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=ORCL))) "/>
</version>
</oracle.manageddataaccess.client>
App.config
59. 59
List All Employees from the HR Schema
using (var dbCon = new OracleConnection(
"Data Source=orcl; User Id=hr; Password=hr"))
{
dbCon.Open();
var cmd = new OracleCommand("SELECT * FROM EMPLOYEES", dbCon);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = (int) reader["EMPLOYEE_ID"];
string firstName = (string) reader["FIRST_NAME"];
string lastName = (string) reader["LAST_NAME"];
Console.WriteLine(id + ": " + firstName + " " + lastName);
}
}
61. 61
Oracle is world's leading RDBMS
Powerful, but complex
Oracle SQL Developer
DB GUI tool for developers
SQL language
SELECT, INSERT, UPDATE, DELETE
PL/SQL – variables, conditions, loops, cursors, …
Accessing from Java – use the Oracle JDBC drivers
Accessing from C# – use the .NET Data Provider for Oracle
Summary