oracle 10g

Post on 16-Apr-2017

792 Views

Category:

Education

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Oracle Databasefor Developers

Introduction to Oracle, SQL Developer, SQL, PL/SQL, …

Svetlin NakovTechnical Trainerwww.nakov.comSoftware Universityhttp://softuni.bg

OracleDatabase

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

Table of Contents

1. Oracle Database Overview2. Installing Oracle Database 12c3. Installing SQL Developer4. Creating DB Schemas and Tables5. SQL Language Basics

SELECT, INSERT, UPDATE, DELETE, …

6. PL/SQL: Procedures, Functions, Triggers7. Accessing Oracle from C# and Java

3

Oracle DatabaseOverview

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?

Installing Oracle 12c / 11g XE

7

Installing Oracle 12c

Typically, Oracle 12c DB Enterprise takes~ 10GB HDD space

8

Installing Oracle 12c – Use a Built-In User

Developers may use "Windows Built-in Account"

for simplified setup

9

Installing Oracle 12c – Location & Password

Select a directory without spaces,

e.g. C:\oracle

Don't select "Container database". It is too complex!

10

Installing Oracle 12c – Be Patient

Usually it takes 20-30 minutes

11

Oracle DB Express Edition (XE) Free, limited, lightweight version 1 CPU, 1 GB RAM, 11 GB storage Only 11g (no 12c version)

Installing Oracle Database XE Download Oracle Database XE 11g Install it in a folder without spaces, e.g. C:\Progra~1\Oracle Remember the admin password (for the users SYS and SYSTEM)

Alternative: Oracle Express Edition (XE)

Use Oracle XE for slower computers

12

OracleServiceORCL / OracleServiceXE The Oracle database engine for the "ORCL" / "XE" instance (SID) The core of the Oracle database

OracleOraDB12Home1TNSListener / OracleXETNSListener Connects Oracle database with client applications (TNS service)

Listens on TCP port 1521 (TNS listener)

Enterprise Manager (EM) console – https://localhost:5500/em Application Express Web interface (APEX) – http://localhost:8080

Oracle Database Services and Ports

Install Oracle 12c DatabaseLive Exercise in Class (Lab)

Oracle SQL DeveloperInstalling and Using SQL Developer

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

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:\oracle\sqldeveloper

3. Run sqldeveloper.exe4. Choose your JDK location

5. Create a start menu shortcut

6. Enjoy

Installing Oracle SQL Developer

17

Connecting to Oracle with SQL Developer

Use "ORCL" or "XE" as SID (System

ID)

18

Executing SQL Commands

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

20

Unlocking the "HR" User (Schema)

21

Connecting with the "HR" User

22

View / Edit Data in the "HR" Shema

Install Oracle SQL Developerand Access the "HR" Schema

Live Exercise in Class (Lab)

Creating DB Schemas and TablesCreating Users, Tables, Relationships, Etc.

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

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

Creating a New User in SQL Developer

Granting "DBA" role is easy but might be

a security risk

28

Creating Tables in SQL Developer: COUNTRIES

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

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!

31

Editing Table Data in SQL Developer

32

Creating Tables in SQL Developer: TOWNS

33

Creating Relationships in SQL Developer

First save the "TOWNS" table, then edit it to add

the foreign key constraint

34

View E/R Diagram

35

Foreign Key Constraint Violation

36

Creating E/R Diagram with Data Modeler

Creating DB Schema "Maria" Holding Countries and Towns (One to Many)

Live Exercise in Class (Lab)

SQL Language – BasicsBasics SQL Commands: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP

SELECT *FROM COUNTRIESWHERE COUNTRY_ID = 'UK'

SELECT c.COUNTRY_NAME AS COUNTRY, r.REGION_NAME AS REGIONFROM COUNTRIES c JOIN REGIONS r ON c.REGION_ID = r.REGION_ID

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_COUNTFROM DEPARTMENTS d JOIN EMPLOYEES e ON e.DEPARTMENT_ID = d.DEPARTMENT_IDGROUP BY d.DEPARTMENT_ID, d.DEPARTMENT_NAMEHAVING COUNT(e.EMPLOYEE_ID) >= 5ORDER BY EMP_COUNT DESC

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

SELECT

WHERE

ORDER BY

SQL: SELECT, WHERE, ORDER BY

SELECT * FROM COUNTRIES

SELECT COUNTRY_ID, REGION_IDFROM COUNTRIES

SELECT * FROM COUNTRIESWHERE COUNTRY_ID = 'UK'

SELECT * FROM COUNTRIESWHERE COUNTRY_ID LIKE 'C%' OR COUNTRY_NAME LIKE 'Un%'

SELECT * FROM COUNTRIESORDER BY COUNTRY_NAME

SELECT * FROM COUNTRIESORDER BY COUNTRY_ID DESCFETCH NEXT 3 ROWS ONLY

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 REGIONFROM COUNTRIES c JOIN REGIONS r ON c.REGION_ID = r.REGION_ID

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

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 DEPARTMENTSSET DEPARTMENT_NAME = 'Brazil Sales and Marketing'WHERE DEPARTMENT_NAME = 'Brazil Sales'COMMIT; -- Save pending changes

45

Delete existing department + commit

Delete all locations in Italy + rollback

SQL: DELETE

DELETE FROM DEPARTMENTSWHERE DEPARTMENT_ID = 320;COMMIT; -- Save pending changes

DELETE FROM LOCATIONSWHERE COUNTRY_ID = (SELECT COUNTRY_ID FROM COUNTRIES WHERE COUNTRY_NAME = 'Italy');ROLLBACK; -- Discard (cancel) pending changes

SQL CommandsLive 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

The PL/SQL LanguageProgramming Logic in the Database

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

PL/SQL – ExampleSET SERVEROUTPUT ONDECLARE 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

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

PL/SQL: Interchange Salaries – ExampleCREATE 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);

Accessing Oracle DB from JavaUsing the Oracle JDBC Driver

Connection

Statement

ResultSet

Oracle DB

setInt(…)

setDate(…)setString(…)

53

Setup a Maven-Based Java Project

<project …> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build></project>

pom.xml

Create a Maven project and specify Java 8 compilation mode(by default Maven uses Java 5)

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

List All Employees from the HR Schemapublic 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); } }}

Accessing Oracle DB from C#Using the Oracle Data Provider for .NET

OracleConnection

OracleCommand

OracleDataReader

Oracle DB

OracleParameter

OracleParameterOracleParameter

57

Reference the Oracle Data Provider from NuGet

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

List All Employees from the HR Schemausing (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); }}

Accessing Oracle from Java and C#Live Exercise (Lab)

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

License This course (slides, examples, demos, videos, homework, etc.)

is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license

63

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education,

Profession and Job for Software Developers softuni.bg

Software University @ Facebook facebook.com/SoftwareUniversity

Software University @ YouTube youtube.com/SoftwareUniversity

Software University Forums – forum.softuni.bg

top related