728x90
반응형
SMALL

변환 함수

* 암시적인 데이터형 변환

* 명시적인 데이터형 변환

 

1. 암시적 형 변환

- 값 할당 시 오라클은 자동으로 변환한다.

From To 비고
VARCHAR2 / CHAR NUMBER 표현식 계산의 경우
VARCHAR2 / CHAR DATE 표현식 계산의 경우
NUMBER VARCHAR2  
DATE VARCHAR2  
select employee_id, first_name, hire_date
from employees
where hire_date='03/06/17';
--char가 DATE형으로 변환
select employee_id, first_name, department_id
from employees
where department_id='40';
--char가 NUMBER타입으로 자동 형 변환

 

2. 명시적 형 변환

변환 함수 설명
TO_CHAR(number [, 'fmt']) 숫자를 문자 타입으로
TO_CHAR(date[, 'fmt']) 날짜를 문자 타입으로
TO_NUMBER(char[, 'fmt']) 숫자를 포함하 문자를 숫자로
TO_DATE(char[, 'fmt']) 날짜를 나타내는 문자를 DATE타입으로

 

3. 날짜를 문자로 변환

TO_CHAR(date, 'fmt')
select first_name, TO_CHAR(hire_date, 'MM/YY') as hiremonth
from employees
where first_name='Steven';

select first_name, to_char(hire_date, 'YYYY"년" MM"월" DD"일"') as hiredate
from employees;

select first_name,to_char(hire_date, 'fmDdspth "of" Month YYYY fmHH:MI:SS AM',
'NLS_DATE_LANGUAGE=english') as hiredate from employees;

 

4. 숫자를 문자로 변환

TO_CHAR(number, 'fmt')
select first_name, last_name,to_char(salary, '$999,999') salary
from employees;

select first_name, last_name, salary*0.123456 salary1,
to_char(salary*0.123456, '$999,999.99') salary2
from employees
where first_name='David';

5. TO_NUMBER 함수

TO_NUMBER(char, 'fmt')
select '$5,500'-4000 from dual; --오류
select to_number('$5,500', '$999,999')-4000 from dual;

 

6. TO_DATE 함수

TO_DATE(char, 'fmt')
select first_name, hire_date
from employees
where hire_date=to_date('2003/06/17','YYYY/MM/DD');

select first_name, hire_date
from employees
where hire_date = to_date('2003년06월17일', 'YYYY"년"MM"월"DD"일"');

7. Null 치환 함수 NVL, NVL2, COALESCE

1) NVL1

NVL(expr1, expr2)
--expr1:널이 있을 수 있는 열
--expr2:널일경우 치환할 값
select first_name, salary + salary*nvl(commission_pct,0) from employees;

2) NVL2

nvl2(expr1, expr2, expr3)
select first_name,
nvl2(commission_pct, salary+salary*commission_pct, salary) as nann_sal
from employees;

3) COALESCE

COALESCE(expr1, ...)
select first_name,
coalesce(salary+salary*commission_pct, salary)as ann_sal
from employees;

 

 

8. 기타 변환 함수

1) LNNVL 

LNNVL(expr1)
select first_name, coalesce(salary*commission_pct,0) as bonus from employees
where salary*commission_pct < 650;

==>null인 것들을 모두 제외하게 됨

select first_name, coalesce(salary*commission_pct,0) as bonus from employees
where lnnvl(salary*commission_pct >= 650);

=>null값도 포함시킴

 

2) DECODE

select job_id, salary, 
decode(job_id, 'IT_PROG', salary*1.10,
'FI_MGR', salary*1.15,
'FI_ACCOUNT', salary*1.20,
salary) as revised_sal
from employees;

 

3) CASE

select job_id, salary,
case job_id when 'IT_PROG' then salary*1.10
when 'FI_MGR' then salary*1.15
when 'FI_ACCOUNT' then salary*1.20
else salary
end as revise_sal
from employees;

=>위와 같은 결과

select employee_id, salary,
case when salary < 5000 then salary*1.2
when salary < 10000 then salary*1.10
when salary < 15000 then salary*1.05
else salary
end as revised_sal
from employees;

 

집합 연산자

1. UNION

- 합집합과 같은 의미

- 중복된 정보는 한 번만 보여줌.

select employee_id, first_name from employees where hire_date like '04%'
union
select employee_id, first_name from employees where department_id=20;

 

2. UNION ALL

- 중복된 정보 포함

select employee_id, first_name from employees where hire_date like '04%'
union all
select employee_id, first_name from employees where department_id=20;

 

3. INTERSECT

- 중복된 행만 출력

- 교집합과 같은 의미

select employee_id, first_name from employees where hire_date like '04%'
intersect
select employee_id, first_name from employees where department_id=20;

 

4. MINUS

- 첫번째 쿼리에만 포함되고 두번째 쿼리에는 없는 데이터를 보여준다.

- 차집합과 같은 의미

select employee_id, first_name from employees where hire_date like '04%'
minus
select employee_id, first_name from employees where department_id=20;

 

728x90
반응형
LIST

'IT > SQL' 카테고리의 다른 글

[SQL] 5. 분석 함수  (0) 2023.05.11
[SQL] 4. 그룹 함수를 이용한 데이터 집계  (0) 2023.05.10
[SQL] 3. 함수 - 1  (0) 2023.05.09
[SQL] 2. SELECT문  (0) 2023.05.08
[SQL] 1. 데이터베이스 소개  (0) 2023.05.08
728x90
반응형
SMALL

함수

1. SQL 함수 개요

- 함수 : 데이터를 조작하기 위해 사용됨.

- 특징 :

1) 데이터 계산 수행

2) 개별적인 데이터 항목 수정

3) 행의 그룹에 대해 결과 조작

4) 출력을 위한 날짜와 숫자 형식 설정

5) 열의 데이터 타입 반환

2. SQL 함수의 두 가지 유형

* 단일행 함수

- 오직 단일행에서만 적용 가능하고 행별로 하나의 결과를 반환

 

* 다중행 함수

- 복수의 행을 조작하여 행의 그룹 당 하나의 결과를 반환

 

3. 단일 행 함수

function_name(column | expression, [arg1, arg2, ...])

- 데이터 값 조작

- 인수(argument)를 받고 하나의 결과 리턴

- 리턴될 각각의 행에 적용

- 행별로 하나의 결과 리턴

- 데이터 타입 수정 가능

- 중첩(nested)될 수 있다.

- 종류 : 문자/숫자/날짜/변환/General 함수

 

문자 함수

select initcap('helloworld') from dual;

1. LOWER, INITCAP, UPPER

select last_name, lower(last_name), initcap(last_name), upper(last_name)
from employees;
select last_name, lower(last_name), initcap(last_name), upper(last_name)
from employees
where lower(last_name)='austin';

2. LENGTH, INSTR

select first_name, length(first_name),instr(first_name,'a')
from employees;

3. SUBSTR, CONCAT

select first_name, substr(first_name,1,3), concat(first_name, last_name)
from employees;

4. LPAD, RPAD

select rpad(first_name,10,'-') as name, lpad(salary,10,'*')as sal
from employees;

5. LTRIM, RTRIM

select ltrim('JavaSpecialist','Java') from dual;
select ltrim(' JavaSpecialist') from dual;
select trim( 'JavaSpecialist ') from dual;

6. REPLACE, TRANSLATE

select replace('JavaSpecialist','Java','BigData') from dual;
select replace('Java Specialist',' ','') from dual;
select translate('javaspecialist','abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyzabc') from dual;

7. 실전 문제

select rpad(substr(first_name,1,3),length(first_name),'*') as name,
lpad(salary,10,'*') as salary 
from employees
where lower(job_id) = 'it_prog';

 

정규표현식 함수

함수 명칭 설명
REGEXP_LIKE 패턴에 이리하는 문자열을 포함하는 행 찾기
LONG 지원X
REGEXP_INSTR 지정한 조건을 만족하는 부분의 최초의 위치를 돌려줌.
REGEXP_SUBSTR 지정한 정규 표현을 만족하는 부분 문자열 반환
REGEXP_REPLACE 지정한 정규 표현을 만족하는 부분을, 지정한 다른 문자열로 치환

1. 정규표현식

- 횟수 지정 메타 문자

메타 문자 기능
? 0회 또는 1회
* 0회 이상
+ 1회 이상
{n} n회 이상
{m,} m회 이상
{m,n} m회 이상 n회 이하

- 메타 문자

메타 문자 기능
. 문자
[] 문자들
[^ ] 부정
^ 처음
$
() 그룹 묶기

- 탈출 문자

탈출 문자 기능
\n n번째 패턴
\w "-"와 영숫자
\W \w 반대
\s 공백
\S 공백 제외
\d 숫자
\D 숫자 제외

- POSIX 문자클래스

문자 클래스 설명
   
   
   
   
   
   
   
   
   

 

2. REGEXP_LIKE 함수

REGEXP_LIKE(source_string, pattern[, match_parameter])
Create table test_regexp (col1 varchar2(10));
insert into test_regexp values('ABCDE01234');
insert into test_regexp values('01234ABCDE');
insert into test_regexp values('abcde01234');
insert into test_regexp values('01234abcde');
insert into test_regexp values('1-234-5678');
insert into test_regexp values('234-567890');

select * from test_regexp
where regexp_like(col1,'[0-9][a-z]');

select * from test_regexp
where regexp_like(col1,'[0-9]{3}-[0-9]{4}$');
select * from test_regexp
where regexp_like(col1,'[[:digit:]]{3}-[[:digit:]]{4}$');
select * from test_regexp
where regexp_like(col1,'^[0-9]{3}-[0-9]{4}');

 

create table qa_master (qa_no varchar(10));

alter table qa_master add constraint qa_no_chk check
(regexp_like(qa_no,
'^[[:alpha:]]{2}-[[:digit:]]{2}-[[:digit:]]{4}$'));

insert into qa_master values('QA-01-0001');
insert into qa_master values('00-01-0001'); --오류

 

3. REGEXP_INSTR 함수

REGEXP_INSTR(source_string, pattern [, start_position
[, occurrence [ , return_option [, match_parameter]]]])
insert into test_regexp values('@!=)(9&%$#');
insert into test_regexp values('자바3');

select col1,regexp_instr(col1,'[0-9]') as data1,
regexp_instr(col1,'%') as data2 from test_regexp;

4. REGEXP_SUBSTR 함수

REGEXP_SUBSTR(source_string, pattern [, start_position [, occurrence [, match_parameter]]])
select col1, regexp_substr(col1, '[C-Z]+') from test_regexp;

5. REGEXP_REPLACE 함수

regexp_replace(source_string, pattern [, replace_string [, start_position [, occurrence [, match_parameter]]]])
select col1, regexp_replace(col1,'[0-2]+','*')
from test_regexp;

 

6. 실전 문제

select first_name, phone_number
from employees
where regexp_like(phone_number,'[0-9]{3}.[0-9]{3}.[0-9]{4}$');

 

select first_name, 
regexp_replace(phone_number, '[0-9]{4}$','****') as phone,
regexp_substr(phone_number, '[0-9]{4}$') as phone2
from employees;

숫자 함수

1. ROUND, TRUNC

select round(45.923,2), round(45.923,0), round(45.923,-1) from dual;

select trunc(45.923,2), trunc(45.923), trunc(45.923,-1) from dual;

 

날짜 함수

select sysdate from dual;

1. 날짜의 연산

- 날짜에서 숫자를 더하거나 빼 날짜 결과를 반환

- 날짜 사이의 일(day) 수를 알기 위해 두 개의 날짜를 뺀다

- 시간을 24로 나누어 날짜에 더한다.

select first_name, (sysdate-hire_date)/7 as "weeks"
from employees
where department_id=60;

2. 날짜 함수

select first_name, sysdate, hire_date, months_between(sysdate, hire_date) as workmonth
from employees
where first_name='Diana';
select first_name, hire_Date, add_months(hire_date, 100)
from employees
where first_name='Diana';
select sysdate, next_day(sysdate,'월')
from dual;
select sysdate, last_day(sysdate) from dual;
select sysdate, round(sysdate), trunc(sysdate) from dual;
select sysdate, round(sysdate), trunc(sysdate) from dual;
select trunc(sysdate, 'Month') from dual;
select trunc(sysdate, 'Year') from dual;
select trunc(to_date('17/03/16'), 'Month') from dual;
select round(to_date('17/03/16'), 'Month') from dual;
select trunc(to_date('17/03/16'), 'Day') from dual;

 

 

 

 

728x90
반응형
LIST

'IT > SQL' 카테고리의 다른 글

[SQL] 5. 분석 함수  (0) 2023.05.11
[SQL] 4. 그룹 함수를 이용한 데이터 집계  (0) 2023.05.10
[SQL] 3. 함수 - 2  (0) 2023.05.09
[SQL] 2. SELECT문  (0) 2023.05.08
[SQL] 1. 데이터베이스 소개  (0) 2023.05.08
728x90
반응형
SMALL

SELECT 문장

1. SELECT

SELECT [DISTINCT] {* | coulumn[[AS] alias], ...}
FROM tablename;
SELECT 하나 이상의 열을 나열합니다.
DISTINCT 중복 제거
* 모든 열 선택
column 명명된 열 선택
AS 열 별칭(alias) 지정
alias 선택된 열을 다른 이름으로 변경
FROM tablename; 열을 포함하는 테이블 명시

 

2. SQL 문장 작성

- 대/소문자 구별X

- 문장이 한 줄 이상일 수 있음

- 키워드는 단축하거나 줄을 나눠 쓸 수 있음

- 절은 대개 줄을 나누어 작성

- 탭과 들여쓰기는 가독성을 위해 사용

SQL> SELECT first_name, last_name, salary
  2  FROM employees;

 

3. 모든 열 선택

SQL> SELECT *
  2  FROM departments;

 

4. 특정 열 선택

SQL> SELECT department_name, location_id
  2> FROM departments;

 

5. 기본 표시 형식

- 디폴트 데이터 자리맞춤을 지정합니다.

- 날짜와 문자 데이터는 왼쪽 정렬됩니다.

- 숫자 데이터는 오른쪽 정렬됩니다.

- 디폴트 열 헤딩은 대문자로 출력됩니다

 

6. 열 별칭(alias) 정의

- 열 헤딩 이름을 변경합니다.

- 계산할 때 유용

- 열 이름 바로 뒤에 두며 AS 별칭 으로 하기도 합니다.

- 공백/특수문자는 인용부호(" ")가 필요합니다.

SQL> SELECT first_name AS 이름, salary 급여
  2  FROM employees;

 

7. 리터럴(literal) 문자 스트링과 연결 연산자

- SELECT 절에 포함된 리터럴은 문자 표현식 또는 숫자 입니다.

- 날짜와 문자 리터럴 값은 단일 인용부호(' ')안에 있어야 합니다.

- 숫자 리터럴은 단일 인용부호(' ')를 사용하지 않습니다.

- 각각의 문자스트링은 리턴된 각 행에 대한 결과입니다.

- ||를 이용하면 값을 연결해 줍니다

SQL> SELECT first_name || ' ' || last_name || '''s salary is $' || salary
  2  AS	"Employee Details"
  3  FROM employees;

 

8. 중복 행과 DISTINCT

- 디폴트 출력은 중복되는 행을 포함하는 모든 행입니다.

- SELECT 절에서 DISTINCT 키워드를 사용하여 중복되는 행을 제거합니다.

 

데이저 제한

1. Selection

- 원하는 행을 선택적으로 조회하는 것

 

2. 선택된 행 제한

- WHERE 절을 사용하여 반환하는 행을 제한

- WHERE 절은 FROM절 다음에 위치

- WHERE 절은 열 이름, 비교 연산자, 비교할 열 이름 또는 값의 목록으로 구성

SELECT [DISTINCT] {*|coulumn[[AS] alis], ...}
FROM table
[WHERE condition(s)];
SELECT first_name, job_id, department_id
FROM employees
WHERE job_id = 'IT_PROG';

 

3. 문자와 날짜

- 문자, 문자열, 날짜는 ''로 둘러쌈.

- 문자 값은 대/소문자 구분, 날짜 값은 형식을 따른다.

- 기본 날짜 형식은 'DD-MON-YY'

SELECT first_name, hire_date
FROM employees
WHERE last_name='King';

 

 

4. 비교 연산자

연산자 설명
= 같다
> 크다
>= 크거나 같다
< 작다
<= 작거나 같다
<> , != 같지 않다

 

5. BETWEEN 연산자

- 값의 범위에 해당하는 값을 출려하기 위해 BEETWEEN 사용

- 하한값 먼저 명시

- 하한값, 상한값 모두 포함

-- 2004년에 입사한 사원
SELECT first_name, salary, hire_date
FROM employees
WHERE hire_date BETWEEN '04/01/01' AND '04/12/31';

6. IN 연산자

- 목록에 값이 있는지 비교

SELECT employee_id, first_name, salary, manager_id
FROM employees
WHERE manager_id IN(101, 102, 103);

 

7. LIKE 연산자

- 검색 문자열에 대한 와일드카드 검색

- 검색 조건은 문자, 날짜 포함 가능

- %는 문자가 없거나 하나 이상 문자들 대신

- _는 하나의 문자 대신

--LIKE연산
SELECT first_name, last_name, job_id, department_id
FROM employees
WHERE job_id LIKE 'IT_%';

 

8. IS NULL 연산자

- IS NULL 연산자로 널인지 테스트

- 널이 아닌 값은 IS NOT NULL

SELECT first_name, manager_id
FROM employees
WHERE manager_id IS NULL;

 

9. 논리 연산자

- AND는 양쪽 조건이 참이어야 TRUE 반환

- OR은 한쪽의 조건이 참이면 TRUE 반환

- NOT 연산자는 뒤의 조건에 반대되는 결과 반환

 

10. 논리 연산자 우선순위

우선순위 연산자
1 모든 비교 연산자
2 NOT
3 AND
4 OR

 

데이터 정렬

- 질의에 의해 검색되는 행을 정렬할 수 있다.

- ORDER BY 절은 SELECT 문장의 가장 뒤에 옴.

- ASC :오름차순

- DSEK : 내림차순

SELECT expr
FROM table
[WEHRE condition(s)]
[ORDER BY {coluumn|expr [[ASC]|DESC];
select first_name, hire_date
from employees
order by hire_date;

select first_name, hire_date from employees
order by hire_date desc;

select first_name, salary*12 as annsal
from employees
order by annsal;

select first_name, salary*12 as annsal
from employees
order by 2;

실습

1. 모든 사원의 사원번호, 이름, 입사일, 급여를 출력하세요.

2. 모든 사원의 이름과 성을 붙여 출력하세요. 열 별칭은 name으로 하세요.

3. 50번 부서 사원의 모든 정보를 출력하세요.

4. 50번 부서 사원의 이름, 부서번호, 직무아이디를 출력하세요.

5. 모든 사원의 이름, 급여 그리고 300달러 인상된 급여를 출력하세요.

6. 급여가 10000보다 큰 사원의 이름과 급여를 출력하세요.

7. 보너스를 받는 사원의 이름과 직무, 보너스율을 출력하세요.

8. 2003년도 입사한 사원의 이름과 입사일 그리고 급여를 출력하세요.(BETWEEN 연산자 사용)

9. 2003년도 입사한 사원의 이름과 입사일 그리고 급여를 출력하세요.(LIKE 연산자 사용)

10. 모든 사원의 이름과 급여를 급여가 많은 사원부터 적은 사원순서로 출력하세요.

11. 위 질의를 60번 부서의 사원에 대해서만 질의하세요.

12. 직무아이디가 IT_PROG 이거나, SA_MAN인 사원의 이름과 직무아이디를 출력하세요.

13. Steven King 사원의 정보를 “Steven King 사원의 급여는 24000달러 입니다” 형식으로 출력하세요.

14. 매니저(MAN) 직무에 해당하는 사원의 이름과 직무아이디를 출력하세요.

15. 매니저(MAN) 직무에 해당하는 사원의 이름과 직무아이디를 직무아이디 순서대로 출력하세요

 

--연습문제
---1
select employee_id, first_name, hire_date, salary
from employees;
--2
select first_name ||' '|| last_name as name
from employees;
--3
select * from employees where department_id=50;
--4
select first_name, department_id, job_id from employees where department_id=50;
--5
select first_name, department_id, salary, salary+300 from employees;
--6
select first_name, salary from employees where salary>10000;
--7
select first_name, job_id, commission_pct from employees
where commission_pct is not null;
--8
select first_name, hire_date,salary from employees
where hire_date between '03/01/01' and '03/12/31';
--9
select first_name,hire_date, salary
from employees
where hire_date like '03%';
--10
select first_name, salary from employees
order by salary desc;
--11
select first_name, salary from employees
where department_id=60
order by salary desc;
--12
select first_name, job_id
from employees
where job_id in('IT_PROG', 'SA_MAN');
--13
select first_name||' '||last_name||' 사원의 급여는 '||salary||'달러입니다.'
from employees
where last_name='King' and first_name='Steven';
--14
select first_name, job_id from employees
where job_id like '%MAN';
--15
select first_name, job_id from employees
where job_id like '%MAN'
order by job_id;
728x90
반응형
LIST

'IT > SQL' 카테고리의 다른 글

[SQL] 5. 분석 함수  (0) 2023.05.11
[SQL] 4. 그룹 함수를 이용한 데이터 집계  (0) 2023.05.10
[SQL] 3. 함수 - 2  (0) 2023.05.09
[SQL] 3. 함수 - 1  (0) 2023.05.09
[SQL] 1. 데이터베이스 소개  (0) 2023.05.08
728x90
반응형
SMALL

개요

1. 관계형 데이터베이스 역사

1.1 역사

- 1960년대 : Flat File

- 1970년대 : Network DBMS, Hierarchical DB

- 1980년대 : 관계형 DBMS

- 1990년대 : 관계형 DBMS, 객체 관계형 DBMS

- 2000년대 : 관계형/객체관계형/객체지향 DBMS

1.2 데이터베이스 시스템에 대한 관계형 모델 제안

- E.F.Codd 박사(1970년 6월)

- “A Relational Model of Data for Large Shared Data Banks” 라는 논문

- RDBMS(Relational Database Management System)의 시초

1.3 관계형 모델의 구성요소

- 개체(object) 혹은 관계(relation)의 집합

- 관계(relation)에 가해지는 연산자의 집합

- 정확성과 일관성을 위한 데이터 무결

 

2. 관계형 데이터베이스 정의

2.1 정의

- 관계형 데이터베이스는 관계들의 모음 또는 이차원 테이블의 모음이다.

2.2 파일 시스템과 데이터베이스 시스템의 차이점

- 데이터 무결성 제공

- 데이터 공유 가능

- 데이터 정확성과 일관성 제공

- 관계 설정을 통한 중복 제거

- 표준화가 가능

 

3. 관계형 데이터베이스 특징

- SQL을 이용한 데이터 조작

- 데이터 무결성 제공

- 트랜잭션 제공

- ACID 규정 준수 : 데이터베이스 트랜잭션이 안전하게 수행된다는 것을 보장하기 위한 성질을 가리키는 용어

원자성(Atomicity) 일관성(Consistency) 독립성(Isolation) 지속성(Durability)
- 트랜잭션과 관련된 작업들이 부분적으로 실행되다가 중단되지 않는 것을 보장하는 능력이다.
- 예를 들어, 자금 이체는 성공할 수도 실패할 수도 있지만 보내는 쪽에서 돈을 빼 오는 작업만 성공하고 받는 쪽에 돈을 넣는 작업을 실패해서는 안된다.
- 원자성은 이와 같이 중간 단계까지 실행되고 실패하는 일이 없도록 하는 것이다.
- 트랜잭션이 실행을 성공적으로 완료하면 언제나 일관성 있는 데이터베이스 상태로 유지하는 것을 의미한다.
- 무결성 제약이 모든 계좌는 잔고가 있어야 한다면 이를 위반하는 트랜잭션은 중단된다.
- 트랜잭션을 수행 시 다른 트랜잭션의 연산 작업이 끼어들지 못하도록 보장하는 것
- 트랜잭션 밖에 있는 어떤 연산도 중간 단계의 데이터를 볼 수 없음을 의미한다.
- 은행 관리자는 이체 작업을 하는 도중에 쿼리를 실행하더라도 특정 계좌간 이체하는 양 쪽을 볼 수 없다. 
- 성공적으로 수행된 트랜잭션은 영원히 반영되어야 함을 의미한다.
- 시스템 문제, DB 일관성 체크 등을 하더라도 유지되어야 함을 의미한다.
- 전형적으로 모든 트랜잭션은 로그로 남고 시스템 장애 발생 전 상태로 되돌릴 수 있다.
- 트랜잭션은 로그에 모든 것이 저장된 후에만 commit 상태로 간주될 수 있다.

 

4. 엔티티(Entity) 관계 모델

4.1 Employees 테이블과 Departments 테이블의 관계 도표 생성

=> 부서에는 0명 이상의 사원을 갖고 있다.

=> 사원은 부서를 0개 혹은 1개를 가진다.

4.2 시나리오(카디널리티)

4.3 ER 모델링의 장점

- 조직에 대한 정보를 정확하고 자세하게 문서화 => 품질보증에 사용

- 정보 요구사항의 범위를 명확히 기술

- 데이터베이스 설계를 쉽게 이해할 수 있는 표본 제공

- 복수 응용프로그램의 통합화를 위한 효과적 프레임워크 제공

 

 

5. 관계형 데이터베이스의 기본 구조

일반적 개념 모델링 DB객체
데이터 집합,
Relation,
관계집합(Relation Set)
개체집합(Entity Set) 테이블(table)
관계집합 중 어떤 행(row) 튜플(tuple), 엔티티(Entity) 레코드(record)
관계집합 중 어떤 열(column) 속성(attribute) 필드(field)

 

6. 테이블 관련 용어

행(row) 테이블에서 각 행은 중복되지 않으며 기본키에 의해 식별된다. 행의 순서는 무의미하다.
열(column) 한 종류의 데이터를 나타내며 한 열의 데이터는 같은 타입을 갖는다.
기본키(primary key) 기본키는 유일하며 null값을 가질 수 없다. 식별자라고 한다.
외래키(foreign key) 다른 테이블의 기본키 혹은 고유키를 참조하여 사용한다.
필드(field) 행과 열이 교차하는 곳을 말하고, 하나의 값만 가진다.
null 필드는 그 안에 값을 안 가질 수 있다.

 

오라클 DBMS

1. 실습 환경 구축

- https://www.oracle.com 접속

- Oracle Database Express Edition 다운로드

Oracle Database Express Edition (XE) Downloads

 

Oracle Database Express Edition (XE) Downloads

Support Oracle Database Express Edition (XE) is a community supported edition of the Oracle Database family. Please go to the Oracle Database XE Community Support Forum for help, feedback, and enhancement requests. Note: Oracle Support Services only provid

www.oracle.com

- SQLDeveloper 다운로드

Oracle SQL Developer Downloads

 

Oracle SQL Developer Downloads

This archive. will work on a 32 or 64 bit Windows OS. The bit level of the JDK you install will determine if it runs as a 32 or 64 bit application. This download does not include the required Oracle Java JDK. You will need to install it if it's not already

www.oracle.com

 

 

2. 계정 초기화 하기

SQL> conn sys /as sysdba
Enter password:
Connected.
SQL> alter session set "_ORACLE_SCRIPT"=true;
Session altered.
SQL> @?/demo/schema/human_resources/hr_main.sql
specify password for HR as parameter 1:
1의 값을 입력하십시오: hr
specify default tablespeace for HR as parameter 2:
2의 값을 입력하십시오: users
specify temporary tablespace for HR as parameter 3:
3의 값을 입력하십시오: temp
specify log path as parameter 4:
4의 값을 입력하십시오: $ORACLE_HOME/demo/schema/log/

 

3. 쿼리 실행

 

4. sample Table

728x90
반응형
LIST

'IT > SQL' 카테고리의 다른 글

[SQL] 5. 분석 함수  (0) 2023.05.11
[SQL] 4. 그룹 함수를 이용한 데이터 집계  (0) 2023.05.10
[SQL] 3. 함수 - 2  (0) 2023.05.09
[SQL] 3. 함수 - 1  (0) 2023.05.09
[SQL] 2. SELECT문  (0) 2023.05.08
728x90
반응형
SMALL
package miniprj.model;

import lombok.Data;

@Data
public class Book {
	// 예약자성함
	   String name;
	   // 체크인날짜
	   String checkIn;
	   // 체크아웃 날짜
	   String checkOut;
	   // 예약한 객실(standard, superior, suite 셋 중 하나)
	   String room;
	   // 예약 비밀번호
	   String password;
}
package miniprj.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class BookDAO implements IBookDAO{

	@Override
	public int deleteBook(String name, String password) {
		int rowCount=0;
		String sql="delete from book where cust_name=? and pwd=?";
		Connection con=null;
		try {
			con=BookDataSource.getConnection();
			PreparedStatement stmt=con.prepareStatement(sql);
			stmt.setString(1, name);
			stmt.setString(2, password);
			rowCount=stmt.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			BookDataSource.closeConnection(con);
		}
		return rowCount;
	}

	@Override
	public int insertBook(Book book) {
		int rowCount=0;
		String sql="insert into book "
				+ "(cust_name, checkin, checkout, room, pwd) values(?,?,?,?,?)";
		Connection con=null;
		try {
			con=BookDataSource.getConnection();
			PreparedStatement stmt=con.prepareStatement(sql);
			stmt.setString(1, book.getName());
			stmt.setString(2, book.getCheckIn());
			stmt.setString(3, book.getCheckOut());
			stmt.setString(4, book.getRoom());
			stmt.setString(5, book.getPassword());
			rowCount=stmt.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			BookDataSource.closeConnection(con);
		}
		return rowCount;
	}

	@Override
	public int updateBook(Book book) {
		String sql="update book set checkin=?, checkout=?, room=? "
				+ "where cust_name=? and pwd=?";
		int rowCount=0;
		Connection con=null;
		System.out.println(book);
		try {
			con=BookDataSource.getConnection();
			PreparedStatement stmt=con.prepareStatement(sql);
			stmt.setString(1, book.getCheckIn());
			stmt.setString(2, book.getCheckOut());
			stmt.setString(3, book.getRoom());
			stmt.setString(4, book.getName());
			stmt.setString(5, book.getPassword());
			rowCount=stmt.executeUpdate();
			
		} catch (Exception e) {
			throw new RuntimeException();
		}finally {
			BookDataSource.closeConnection(con);
		}

		return rowCount;
	}
	public boolean login(String name, String password) {
		String sql="select * from book where cust_name=? and pwd=?";
		int rowCount=0;
		Connection con=null;
		try {
			con=BookDataSource.getConnection();
			PreparedStatement stmt=con.prepareStatement(sql);
			stmt.setString(1, name);
			stmt.setString(2, password);
			ResultSet rs=stmt.executeQuery();
			if (rs.next()) {
				return true;
			}else{
				System.out.println("일치하는 정보가 없습니다.");
				return false;
			}
		}catch (Exception e) {
			return false;
		}
	}

	@Override
	public int getBookCount() {
		String sql="select count(*) from book";
		int rowCount=0;
		Connection con=null;
		try {
			con=BookDataSource.getConnection();
			PreparedStatement stmt=con.prepareStatement(sql);
			ResultSet rs=stmt.executeQuery();
			rs.next();
			rowCount=rs.getInt(1);
		} catch (Exception e) {
			throw new RuntimeException();
		}finally {
			BookDataSource.closeConnection(con);
		}
		return rowCount;
	}

	@Override
	public Book getOne(String name, String password) {
		String sql="select * from book where cust_name=? and pwd=?";
		Connection con=null;
		Book book=new Book();
		try {
			con=BookDataSource.getConnection();
			PreparedStatement stmt=con.prepareStatement(sql);
			stmt.setString(1, name);
			stmt.setString(2, password);

			ResultSet rs=stmt.executeQuery();
			while(rs.next()) {
				book.setName(rs.getString("cust_name"));
				book.setCheckIn(rs.getString("checkin"));
				book.setCheckOut(rs.getString("checkout"));
				book.setRoom(rs.getString("room"));
				book.setPassword(rs.getString("pwd"));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}finally {
			BookDataSource.closeConnection(con);
		}
		return book;
	}

	@Override
	public ArrayList<Book> getAllBooks() {
		// TODO Auto-generated method stub
		ArrayList<Book> list = new ArrayList<>();
		String sql = "select * from book";
		Connection con = null;
		
		try {
			con = BookDataSource.getConnection();
			PreparedStatement stmt = con.prepareStatement(sql);

			ResultSet rs = stmt.executeQuery();

			while(rs.next()) {
				Book book = new Book();
				book.setName(rs.getString("cust_name"));
				book.setRoom(rs.getString("room"));
				book.setPassword(rs.getString("pwd"));
				book.setCheckIn(rs.getString("checkin"));
				book.setCheckOut(rs.getString("checkout"));
				list.add(book);
			}
		}catch(SQLException e) {
			throw new RuntimeException(e);
		} finally {
			BookDataSource.closeConnection(con);
		}

		return list;

	}


}
package miniprj.model;

import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;

public class BookDataSource {
	private static final String DRIVER = "oracle.jdbc.OracleDriver";
	private static final String URL = "jdbc:oracle:thin:@localhost:1521:xe";
	private static final String USERNAME = "hr";
	private static final String PASSWORD = "hr";
	
	private static BasicDataSource dataSource;
	
	static {
		try {
			dataSource = new BasicDataSource();
			dataSource.setDriverClassName(DRIVER);            
			dataSource.setUrl(URL);
			dataSource.setUsername(USERNAME);                                  
			dataSource.setPassword(PASSWORD);  
			dataSource.setInitialSize(10);
			dataSource.setMaxTotal(10);
			System.out.println("DataSource created");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	public static Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}

	public static void closeConnection(Connection con) {
		if(con!=null) {
			try {
				con.close();
			}catch(Exception e) {}
		}
	}
}
package miniprj.model;

import java.util.ArrayList;

public interface IBookDAO {
	public int deleteBook(String name, String password);
	public int insertBook(Book book);
	public int updateBook(Book book);
	
	public int getBookCount();
	public Book getOne(String name, String password);
	public ArrayList<Book> getAllBooks();
}
package miniprj;

import java.util.List;
import java.util.Scanner;

import miniprj.model.Book;
import miniprj.model.BookDAO;

public class BookWin {
	static boolean isCustomer;
	   static boolean isAdmin;
	   private static  Scanner scan = new Scanner(System.in);
	   static BookDAO bookDao = new BookDAO();
	   static String name = null;
	   static String pwd = null;

	   // 호텔 예약 리스트
	   public static void list(Book list) {
	      System.out.printf("%-6s%-12s%-16s%-40s",list.getName(), list.getCheckIn(), list.getCheckOut(), list.getRoom());
	      System.out.println();
	   }

	   public static void mainMenu() {
	      System.out.println();
	      System.out.println("--------------------------------------------------------");
	      System.out.println("메인메뉴: 1.예약 | 2.조회 | 3.수정 | 4.삭제 | 5.로그아웃 | 6.종료");
	      System.out.println("메뉴선택: ");
	      String menuNo = scan.nextLine();
	      System.out.println();

	      switch(menuNo) {
	      case "1" -> {
	         Book book = new Book();

	         System.out.print("예약자: ");
	         book.setName(scan.nextLine());
	         System.out.print("체크인 날짜: ");
	         book.setCheckIn(scan.nextLine());
	         System.out.print("체크아웃 날짜: ");
	         book.setCheckOut(scan.nextLine());
	         System.out.print("객실: ");
	         book.setRoom(scan.nextLine());
	         System.out.println("비밀번호: ");
	         book.setPassword(scan.nextLine());

	         bookDao.insertBook(book);
	         break;
	      }

	      case "2" -> {
	         System.out.println("[호텔 예약관리 시스템]");
	         System.out.println("--------------------------------------------------------");
	         System.out.printf("%-6s%-12s%-16s%-40s", "성함","체크인 날짜","체크아웃 날짜","객실");
	         System.out.println("--------------------------------------------------------");
	         if (isAdmin) {
	            List<Book> list = bookDao.getAllBooks();
//	            System.out.println(list);
	            for(int i=0;i<list.size();i++) {
	               list(list.get(i));
	            }
	         } else if(isCustomer) {
	            Book book = bookDao.getOne(name, pwd);
	            list(book);
	         }
	         break;
	      }

	      case "3" -> {
	         Book book = bookDao.getOne(name, pwd);

	         System.out.print("체크인 날짜: ");
	         book.setCheckIn(scan.nextLine());
	         System.out.print("체크아웃 날짜: ");
	         book.setCheckOut(scan.nextLine());
	         System.out.print("객실: ");
	         book.setRoom(scan.nextLine());

	         bookDao.updateBook(book);
	         break;

	      }
	      case "4" -> {
	         Book onesBook = bookDao.getOne(name, pwd);
	         if(!onesBook.getName().equals(name)) {
	            System.out.println("예약건이 없습니다.");
	            break;
	         } 

	         int rowCount = bookDao.deleteBook(name, pwd);
	         System.out.println(rowCount + "건의 에약이 취소되었습니다.");
	         break;
	      }
	      case "5" -> {
	         isAdmin = false;
	         isCustomer = false;
	         name = null;
	         pwd = null;
	         loginMenu();
	         break;
	      }
	      case "6" -> {
	         System.out.println("프로그램이 종료되었습니다.");
	         System.exit(0);
	      }
	      }
	   }

	   public static boolean loginMenu() {
	      System.out.println();
	      System.out.println("--------------------------------------------------------");
	      System.out.println("성함을 입력하세요: ");
	      name = scan.nextLine();
	      System.out.println("비밀번호를 입력하세요: ");
	      pwd = scan.nextLine();

	      if(name.equals("admin") && pwd.equals("admin")) {
	         isAdmin = true;
	         return true;
	      } else if(bookDao.login(name, pwd)){
	         isCustomer = true;
	         mainMenu();
	         return true;
	      } else {

	         System.out.println("회원정보가 일치하지 않습니다.");
	         return false;
	      }


	   }

	   public static void main(String[] args) {
	      while(true) {
	         if(loginMenu()) {
	        	 while(isAdmin || isCustomer) {
	        		 mainMenu();
	        	 }
	            
	         }

	      }
	   }

}
728x90
반응형
LIST

'IT > JAVA' 카테고리의 다른 글

[JAVA] #19 데이터베이스 입출력(게시판 프로그램)  (1) 2023.05.02
[JAVA] #18 입출력 스트림  (0) 2023.05.01
[JAVA] #17 스트림 요소 처리  (0) 2023.05.01
[JAVA] #16 람다식  (0) 2023.04.27
[JAVA] #15 컬렉션 자료구조  (0) 2023.04.27
728x90
반응형
SMALL
package ch20.oracle.sec12;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;


public class BoardExample {
	//매개변수
	private static Scanner scanner = new Scanner(System.in);
	private static Connection con=null;
	private static final String url="jdbc:oracle:thin:@localhost:1521:xe";
	
	
   	//게시물 목록 출력
	public static void list() {
		System.out.println();
		System.out.println("[게시물 목록]");
		System.out.println("--------------------------------------------------");
		System.out.printf("%-6s%-12s%-16s%-40s\n","no","writer","date","title");
		System.out.println("--------------------------------------------------");
		
		try {
			String sql="select * from boards order by bno desc";
			PreparedStatement pstmt=con.prepareStatement(sql);
			ResultSet rs=pstmt.executeQuery();
			
			while(rs.next()) {
				Board board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setBtitle(rs.getString("btitle"));
				board.setBcontent(rs.getString("bcontent"));
				board.setBwriter(rs.getString("bwriter"));
				board.setBDate(rs.getDate("bdate"));
				System.out.printf("%-6s%-12s%-16s%-40s\n", 
						board.getBno(), board.getBwriter(),board.getBDate(),board.getBtitle());
			}
			rs.close();
			pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
			exit();
		}
        //메뉴 부르기
		mainMenu();
	}
	
    //메뉴
	public static void mainMenu() {
		System.out.println();
		System.out.println("--------------------------------------------------");
		System.out.println("메인 메뉴 : 1.Create | 2.Read | 3.Clear | 4.Exit");
		System.out.print("메뉴 선택: ");
		int menu = scanner.nextInt();
		scanner.nextLine();
		switch (menu) {
		case 1 -> create();
		case 2 -> read();
		case 3 -> clear();
		case 4 -> exit();
		default -> System.out.println("메뉴를 잘못 입력함.");
		}
	}
	
    //1번 create
    //데이터 생성 insert
	private static void create() {
		Board board = new Board();
		System.out.println("[새 게시물 입력]");
		System.out.print("제목: ");
		board.setBtitle(scanner.nextLine());
		System.out.print("내용: ");
		board.setBcontent(scanner.nextLine());
		System.out.print("작성자: ");
		board.setBwriter(scanner.nextLine());
		
		System.out.println("--------------------------------------------------");
		System.out.println("보조 메뉴: 1.OK | 2.Cancel");
		System.out.print("메뉴 선택: ");
		int menu=scanner.nextInt();

		if(menu==1) {
			try {
				String sql="insert into boards (bno, btitle, bcontent, bwriter, bdate)"
						+ " values(SEQ_BNO.NEXTVAL,?,?,?,sysdate)";
				PreparedStatement pstmt = con.prepareStatement(sql);
				pstmt.setString(1, board.getBtitle());
				pstmt.setString(2, board.getBcontent());
				pstmt.setString(3, board.getBwriter());
				pstmt.executeUpdate();
				pstmt.close();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				exit();
			}
		}
		list();
	}
	
    //2번 read
    //데이터 가져오기 select    
	private static void read() {
		System.out.println("[게시물 읽기");
		System.out.print("bno: ");
		int no=scanner.nextInt();
		scanner.nextLine();
		try {
			String sql="select * from boards where bno = ?";
			PreparedStatement stmt=con.prepareStatement(sql);
			stmt.setInt(1, no);
			ResultSet rs=stmt.executeQuery();
			if(rs.next()) {
				Board board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setBtitle(rs.getString("btitle"));
				board.setBcontent(rs.getString("bcontent"));
				board.setBwriter(rs.getString("bwriter"));
				board.setBDate(rs.getDate("bdate"));
				System.out.println("#############");
				System.out.println("번호: "+board.getBno());
				System.out.println("제목: "+board.getBtitle());
				System.out.println("내용: "+board.getBcontent());
				System.out.println("작성자: "+board.getBwriter());
				System.out.println("날짜: "+board.getBDate());
			
				System.out.println("--------------------------------------------------");
				System.out.println("보조 메뉴: 1.Update | 2.Delete | 3.List");
				System.out.print("메뉴 선택: ");
				int menu=scanner.nextInt();
				scanner.nextLine();

				if(menu==1) {
					update(board);
				}else if(menu==2) {
					delete(board);
				}
			}
			rs.close();
			stmt.close();
		} catch (Exception e) {
			e.printStackTrace();
			exit();
		}
		
		list();
	}
	
    //2-1번 update
    //데이터 수정 update
	public static void update(Board board) {
		System.out.println("[수정 내용 입력]");
		System.out.print("제목: ");
		board.setBtitle(scanner.nextLine());
		System.out.print("내용: ");
		board.setBcontent(scanner.nextLine());
		System.out.print("작성자: ");
		board.setBwriter(scanner.nextLine());
		
		System.out.println("--------------------------------------------------");
		System.out.println("보조 메뉴: 1.OK | 2.Cancel");
		System.out.print("메뉴 선택: ");
		int menu=scanner.nextInt();
		
		if(menu==1) {
			try {
				String sql="update boards set btitle=?, bcontent=?, bwriter=? where bno=?";
				PreparedStatement stmt=con.prepareStatement(sql);
				stmt.setString(1, board.getBtitle());
				stmt.setString(2, board.getBcontent());
				stmt.setString(3, board.getBwriter());
				stmt.setInt(4, board.getBno());
				stmt.executeUpdate();
				stmt.close();
			} catch (Exception e) {
				e.printStackTrace();
				exit();
			}
		}
		list();
	}
    
    //2-2번 delete
    //데이터 삭제 delete
	public static void delete(Board board) {
		try {
			String sql="delete from boards where bno=?";
			PreparedStatement stmt=con.prepareStatement(sql);
			stmt.setInt(1, board.getBno());
			stmt.executeUpdate();
			stmt.close();
		} catch (Exception e) {
			e.printStackTrace();
			exit();
		}
		list();
		
	}
	
    //3번 clear
    //데이터 모두 삭제 truncate
	private static void clear() {
		System.out.println("[게시물 전체 삭제]");
		System.out.println("--------------------------------------------------");
		System.out.println("보조 메뉴: 1.Ok | 2.Cancel");
		System.out.print("메뉴 선택: ");
		int menu=scanner.nextInt();
		scanner.nextLine();
		if(menu==1) {
			try {
				String sql="truncate table boards";
				PreparedStatement stmt=con.prepareStatement(sql);
				stmt.executeUpdate();
				stmt.close();
			} catch (Exception e) {
				e.printStackTrace();
				exit();
			}
		}
		list();
	}
    
    //4번 exit
	private static void exit() {
		if(con!=null) {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO: handle exception
			}
		}
		System.out.println("***게시판 종료***");
		System.exit(0);
	}
    
    //main
	public static void main(String[] args) {
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			con = DriverManager.getConnection(url,"hr","hr");
			
		} catch (Exception e) {
			e.printStackTrace();
			exit();
		} finally {
			list();
		}
		
		
	}
}
728x90
반응형
LIST

'IT > JAVA' 카테고리의 다른 글

[JAVA] 호텔 예약 관리 프로그램  (0) 2023.05.08
[JAVA] #18 입출력 스트림  (0) 2023.05.01
[JAVA] #17 스트림 요소 처리  (0) 2023.05.01
[JAVA] #16 람다식  (0) 2023.04.27
[JAVA] #15 컬렉션 자료구조  (0) 2023.04.27
728x90
반응형
SMALL

입출력 스트림

* 바이트 스트림 : 그림, 멀티미디어, 문자 등 모든 종류의 데이터를 입출력할 때 사용

* 문자 스트림 : 문자만 입출력할 때 사용

=> java.io 패키지 사용

 

구분 바이트 스트림 문자 스트림
입력 스트림 출력 스트림 입력 스트림 출력 스트림
최상위 클래스 InputStream OutputStream Reader Writer
하위 클래스(ex) XxxInputStream
FileInputStream
XxxOutputStream
FileOutputStream
XxxReader
FileReader
XxxWriter
FilreWriter

바이트 출력 스트림

OutputStream은 바이트 출력 스트림의 최상위 클래스로 추상 클래스이다.

리턴 타입 메소드 설명
void write(int b) 1byte를 출력
void write(byte[] b) 매개값으로 주어진 배열b의 모든 바이트를 출력
void write(byte[] b, int off, int len) 매개값으로 주어진 배열b[off]부터 len개의 바이트를 출력
void flush() 출력 버퍼에 잔류하는 모든 바이트를 출력
void close() 출력 스트림을 닫고 사용 메모리 해제

1바이트 출력

public class WriteExample{
	public class void main(String[] args){
    	try{
        	OutputStream os = new FileOutputStream("test1.db");
            
            byte a =10;
            byte b =20;
            byte c =30;
            
            os.write(a);
            os.write(b);
            os.write(c);
            
            os.flush();
            os.close();
        }catch(IOException e){
        	e.printStackTrace();
        }
    }
}

 

바이트 배열 출력

public class WriteExample{
	public static void main(String[] args){
    	try{
        	OutputStream os = new FileOutputStream("test2.db");
            byte[] array = {'A','B','C'};
            
            os.write(array);
            os.flush();
            os.close();
            
        }catch(IOException e){
        	e.printStackTrace();
        }
    }
}

 

바이트 배열 일부분 출력

public class WriteExample{
	public static void main(String[] args){
    	try{
        	OutputStream os = new FileOutputStream("test3.db");
            byte[] array = {'A','B','C','D','E'};
            
            os.write(array,1,3); //B C D 출력
            os.flush();
            os.close();
            
        }catch(IOException e){
        	e.printStackTrace();
        }
    }
}

 

바이트 입력 스트림

InputStream은 바이트 입력 스트림의 최상위 클래스로 추상 클래스이다.

리턴 타입 메소드 설명
int read() 1byte 읽은 후 읽은 바이트를 리턴
int read(byte[] b) 읽은 바이트를 매개값으로 주어진 배열에 저장 후 읽은 바이트 수를 리턴
void close() 입력 스트림을 닫고 사용 메모리 해제

 

1바이트 읽기

public class ReadExample{
	public static void main(String[] args){
    	try{
        	InputStream is = new FileInputStream("test1.db");
            
            whie(True){
            	int data = is.read();
                if(data == -1) break;
                System.out.println(data);
            }
            
            is.close();
        }catch(FileNotFoundException e){
        	e.printStrackTrace();
        }catch(IOException e){
        	e.printStackTrace();
        }
    }
}

 

바이트 배열로 읽기

public class ReadExample{
	public static void main(String[] args){
    	try{
        	InputStream is = new FileInputStream("test2.db");
            
            byte[] data = new byte[100];
            
            while(true){
            	int num = is.read(data);
                if(num == -1) break;
                for(int i=0; i<num; i++){
                	System.out.println(data[i]);
                }
            }
            
            is.close();
        }catch(FileNotFoundException e){
        	e.printStackTrace();
        }catch(IOException e){
        	e.printStackTrace();
        }
    }
}

 

바이트 배열 읽고 바로 출력하기

public class ReadExample{
	public static void main(String[] args){
    	try{
        	InputStream is = new FileInputStream("test.txt");
            OutputStream os = new FileOutputStream("test2.txt");
            
            byte[] data = new byte[100];
            
            while(true){
            	int num = is.read(data);
                if(num == -1) break;
                os.write(data,0,num);
            }
            os.flush();
            os.close();            
            is.close();
            
            System.out.prinln("복사가 되었습니다");
        }catch(FileNotFoundException e){
        	e.printStackTrace();
        }catch(IOException e){
        	e.printStackTrace();
        }
    }
}

 

문자 입출력 스트림

InputStream과 OutputSTream에 대응하는 문자 입출력 스트림으로는 Reader와 Writer가 있다.

 

문자 출력

리턴 타입 메소드 설명
void write(int c) 매개값으로 주어진 한 문자를 출력
void write(char[] cbuf) 매개값으로 주어진 배열의 모든 문자를 출력
void write(char[] cbuf, int off, int len) 매개값으로 주어진 배열에서 cbuf[off]부터 len개까지의 문자를 출력
void flush() 버퍼에 잔류하는 모든 문자를 출력
void close() 출력 스트림을 닫고 사용 메모리를 해제

 

public class WriteExample{
	public static void main(String[] args){
    	try{
        	Writer writer = new FileWriter("text.txt");
            
            //한 문자씩 출력
            char a = 'A';
            writer.write(a);
            char b = 'B';
            writer.write(b);
            
            //char 배열 출력
            char[] arr={'C','D','E'};
            writer.write(arr);
            
            //문자열 출력
            writer.write("FGH");
            
            writer.flush();
            writer.close();
        }catch(IOException e){
        	e.printStacTrace();
        }
    }
}

 

문자 읽기

메소드 설명
int read() 1개의 문자를 읽고 리턴
int read(char[] cbuf) 읽은 문자들을 매개값으로 주어진 문자 배열에 저장하고 읽은 수를 리턴
void close() 입력 스트림을 닫고, 사용 메모리 해제
public class ReadExample{
	public static void main(String[] args){
    	try{
        	Reader reader = null;
            
            //한 문자씩
            reader = new FileReader("test.txt");
            while(true){
            	int data = reader.read();
                if(data == -1) break;
                System.out.println((char)data);
            }
            reader.close();
            
            reader = new FileReader("test.txt");
            char[] data = new char[100];
            while(true){
            	int num=reader.read(data);
                if(num==-1) break;
                for(int i=0; i<num; i++){
                	System.out.print(data[i]);
                }
            }
            reader.close();        
        }catch(FileNotFoundException e){
        	e.printStackTrace();
        }catch(IOException e){
        	e.printStackTrace();
        }
    }
}

 

보조 스트림

보조 스트림 기능
InputStreamReader / OutputStreamWriter 바이트 스트림을 문자 스트림으로 변환
BufferdInputStream, BufferedOutputStream
BufferedReader, BufferedWriter
입출력 성능 향상
DataInputStream, DataOutputStream 기본 타입 데이터 입출력
PrintStream, PrintWriter 줄바꿈 처리 및 형식화된 문자열 출력
ObjectInputStream, ObjectOutputStream 객체 입출력

 

문자 변환 스트림

InputStream을 Reader로 변환

InputStream is = new FileInputStream("text.txt");
Reader reader = new InputStreamReader(is);

OutputStream을 Writer로 변환

OutputStream os = new FileOutputStream("text.txt");
Writer writer = new OutputStreamWriter(os);

 

입출력 성능 향상 스트림

BufferedInputStream bis = new BufferedInputStream(바이트 입력 스트림);
BufferedOutputStream bos = new BufferedOutputStream(바이트 출력 스트림);
BufferedReader br=new BufferedReader(문자 입력 스트림);
BufferedWriter bw = new BufferedWriter(문자 출력 스트림);

 

기본 타입 스트림

바이트 스트림에 DataInputStream과 DataOutputStream 보조 스트림을 연결하면 기본 타입인 boolean, char, short, int, long, double 값을 입출력할 수 있다.

DataInputStream dis=new DataInputStream(바이트 입력 스트림);
DataOutputStream dos = new DataOutputStream(바이트출력 스트림);

 

프린트 스트림

프린트 스트림은 print(), println(), prinf() 메소드를 갖고 있는 보조 스트림이다.

PrintStream ps = new PrintStream(바이트 출력 스트림);
PrintWriter pw = new PrintWriter(문자 출력 스트림);

 

객체 스트림

*직렬화 : 객체를 출력하기 위해 필드값을 일렬로 늘어선 바이트로 변경

*역직렬화 : 직렬화된 바이트를 객체의 필드값으로 복원하는 것

ObjectInputStream ois = new ObjectInputStream(바이트 입력 스트림);
ObjectOutputStream oos = new ObjectOutputStream(바이트 출력 스트림);

oos.writeObject(객체);
객체타입 변수 = (객체타입)ois.readObject();

 

728x90
반응형
LIST
728x90
반응형
SMALL

스트림이란?

컬렉션 및 배열에 저장된 요소를 반복 처리하기 위해서 for문 / Iterator(반복자)를 이용했다.

List<String> list = ...;
for(int i =0; i<list.size(); i++){
	String item = list.get(i);
}
Set<String> set = ...;
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()){
	String item = iterator.next();
}

Java 8부터 스트림을 사용할 수 있다.

*스트림 : 요소들이 하나씩 흘러가면서 처리된다.

Stream<String> stream = list.stream();
stream.forEach( 
	item -> System.out.println(item)
);

* Stream과 Iterator의 차이점

1) 내부 반복자이므로 처리 속도가 빠르고 병렬 처리에 효율적이다.
2) 람다식으로 다양한 요소 처리를 정의할 수 있다.
3) 중간 처리와 최종 처리를 수행하도록 파이프 라인을 형성할 수 있다.

내부 반복자

for문과 Iterator는 컬렉션의 요소를 컬렉션 바깥쪽으로 반복해서 가져와 처리 => 외부 반복자

스트림은 컬렉션 내부에서 요소를 반복하여 처리 => 내부 반복자

중간 처리와 최종 처리

스트림은 하나 이상 연결될 수 있다.  사진을 보면 오리지날->중간 스트림->매핑 중간 스트림으로 연결된다

=> 스트림 파이프라인이라고 한다.

//Student 스트림
Stream<Student> studentStream = list.stream();
//score 스트림
IntStream scoreStream = studentStream.mapToInt(student->student.getScore());
//평균 계산
double age = scoreStream.average().getAsDouble();
//메소드 체이닝 패턴을 이용해 간결하게 작성
double avg = list.stream()
	.mapToInt(student -> student.getScore())
    	.average()
    	.getAsDouble();

 

리소스로부터 스트림 얻기

컬렉션으로부터 스트림 얻기

public class Product{
	private int pno;
    private String name;
    
    public Product(int pno, String name){
		this.pno = pno;
        this.name = name;
	}
    
    @Override
    public String toString(){
    	return new StringBuilder()
        	.append("{")
            .append("pno : " +pno+", ")
            .append("name: " + name + ", ")
            .append("}")
            .toString();

    }
}
public class StreamExample{
	public static void main(String[] args){
    	List<Product> list = new ArrayList<>();
        for( int i =1; i<=5; i++){
        	list.add(new Product(i, "상품"+i);
        }
        
        Stream<Product> stream = list.stream();
        stream.forEach(p->System.out.prinln(p));
    }
}

 

배열로부터 스트림 얻기

java.uti.Arrays 클래스 이용

public class StreamExample{
	public void main(String[] args){
    	String[] strArray = {"홍길동", "김준규", "이다빈"};
        Stream<String> strStream = Arrays.stream(strArray);
        strStream.forEach(item -> System.out.print(item+ ", "));
        System.out.println();
        
        int[] intArr = {1,2,3,4,5};
        IntStream intStream = Arrays.stream(intArr);
        intStream.forEach(item -> System.out.print(item+", "));
    }
}

 

요소 걸러내기(필터링)

리턴 타입 메소드(매개변수) 설명
Stream
IntStream
LongStream
DoubleStream
distinct() - 중복제거
filter() - 조건 필터링
- 매개 타입을 요소 타입에 따른 함수형
인터페이스이므로 람다식으로 작성 가능

 

요소 변환(매핑)

mapXxxx사용.

mapXxx의 매개변수의 타입인 Function은 매개값을 리턴값으로 벼환하는 함수형 인터페이스로 applyXxx() 추상메소드가 있다.

Studentlist.stream()
	.mapToInt(s->s.getScore())
    .forEach(score -> System.out.prinln(score));

 

요소 정렬

Comparable 구현 객체의 정렬

public class Xxx implements Comparable {
	...
}

List<Xxx> list = new ArrayList<>();
Stream<Xxx> stream = list.stream();
Stream<Xxx> orderedStream = stream.sorted();

//객체가 Comparable을 구현하고 있어야 sorted()메소드를 사용해 정렬할 수 있다.
//역으로 정렬
Stream<Xxx> reverseOrderedStream = stream.sorted(Comparator.reverseOrder());

 

Comparator를 이용한 정렬

sorted((o1,o2)-> {...})

- o1이 o2보다 작으면 음수, 같으면 0, 크면 양수를 리턴한다

 

요소를 하나씩 처리(루핑)

리턴 타입 메소드 설명
XxxStream peek 반복
void forEach 반복

 

728x90
반응형
LIST

'IT > JAVA' 카테고리의 다른 글

[JAVA] #19 데이터베이스 입출력(게시판 프로그램)  (1) 2023.05.02
[JAVA] #18 입출력 스트림  (0) 2023.05.01
[JAVA] #16 람다식  (0) 2023.04.27
[JAVA] #15 컬렉션 자료구조  (0) 2023.04.27
[JAVA] #14 멀티 스레드  (0) 2023.04.26
728x90
반응형
SMALL

람다식이란?

- 함수형 프로그래밍. 함수 역할을 하는 매개변수를 가진 중괄호 블럭.

//람다식
(매개변수, ...) -> {처리 내용}

* 사용 예시

public interface Calculable{
	//추상메소드
    void calculate(int x, int y);
}
//익명 구현 객체
new Calculable(){
	@Override
    public void calculate(int x, int y){처리 내용}
}
//람다식 표현 방법
(x,y) -> {처리 내용}
public static void main(String[] args){
	action((x,y)->{
		int result = x+y;
        System.out.println(result);
	}
}

public static void action(Calculable calculable){
	int x=10;
    int y=4;
    calculable.calculate(x,y);
}

* 함수형 인터페이스 : 인터페이스가 단 하나의 추상 메소드를 가질 때. => 이를 보장하기 위해 @FunctionalInterface 어노테이션을 추가한다.

 

 

매개변수가 없는 람다식

()->{
	실행문;
        실행문;
}
() -> 실행문

 

매개변수가 있는 람다식

(타입 매개변수, ...)->{
	실행문;
    	실행문;
}
(타입 매개변수, ...)-> 실행문
(var 매개변수, ...) ->{
	실행문;
    	실행문;
}
(var 매개변수,...)->실행문
(매개변수, ...)->{
	실행문;
    	실행문;
}
(매개변수,...)->실행문

 

리턴값이 있는 람다식

(매개변수, ...)->{
	실행문;
    	return 값;
}
(매개변수, ...) -> return 값
(매개변수, ...)->값

 

메소드 참조

*(::)

1. interface method의 매개변수가 같은 메서드가 실행

2. 람다식 실행구문이 1개인 경우만!

3. 반드시 리턴값 가져야함.

(left,right)->Math.max(left,right);

Math :: max;

 

생성자 참조

(a,b) ->{return new Class(a,b);}

Class::new //생성자 참조
728x90
반응형
LIST

'IT > JAVA' 카테고리의 다른 글

[JAVA] #18 입출력 스트림  (0) 2023.05.01
[JAVA] #17 스트림 요소 처리  (0) 2023.05.01
[JAVA] #15 컬렉션 자료구조  (0) 2023.04.27
[JAVA] #14 멀티 스레드  (0) 2023.04.26
[JAVA] #13 제네릭  (0) 2023.04.24
728x90
반응형
SMALL

컬렉션 프레임워크

 

인터페이스 분류 특징 구현 클래스
Collection List - 순서를 유지하고 저장
- 중복 저장 가능
ArrayList, Vector,
LinkedList
Set - 순서를 유지하고 저장
- 중복 저장 불가능
HashSet, TreeSet
Map - 키와 값으로 구성된 엔트리 저장
- 키는 중복 저장 안됨
HashMap, Hashtable,
TreeMap, Properties

 

List 컬렉션

List컬렉션은 인덱스로 관리한다.

기능 메소드 설명
객체
추가
boolean add(E e) 주어진 객체를 맨 끝에 추가
void add(int index, E element) 주어진 인덱스에 객체를 추가
set(int index, E element) 주어진 인덱스의 객체를 새로운 객체로 바꿈
객체
검색
boolean contains(Object o) 주어진 객체가 저장되어 있는지 여부
E get(int index) 주어진 인덱스에 저장된 객체 리턴
isEmpty() 컬렉션이 비어있는지 검사
int size() 저장되어 있는 전체 객체 수 리턴
객체
삭제
void clear() 저장된 모든 객체 삭제
E remove(int index) 주어진 인덱스에 저장된 객체 삭제
boolean remove(Object o) 주어진 객체를 삭제

 

ArrayList

- List컬렉션 중 가장 많이 사용

- ArrayList에 add로 객체 추가 시 배열에 객체가 저장되며, 일반 배열과 달리 길이 제한이 없다.

- 객체 자체가 아닌 객체의 번지를 저장한다. 동일한 객체 저장도 가능하며, 동일한 번지가 저장된다.

//생성방법
ArrayList<E> list = new ArrayList<E>(); //지정된 E타입 객체만 저장 가능
ArrayList<E> list = new ArrayList<>(); //지정된 E타입 객체만 저장 가능
ArrayList list = new ArrayList(); //모든 타입 객체 저장 가능

* 특정 index 객체를 제거하면 바로 뒤부터 끝까지 모두 앞으로 한 칸씩 당겨진다.

* 특정 index에 객체를 추가하면 해당 인덱스부터 끝까지 뒤로 한 칸씩 밀려진다.

 

Vector

ArrayList와 동일한 내부 구조를 가졌지만 Vector는 동기화된 메소드로 구성되어 있어 멀티 스레드가 동시에 Vector() 메소드를 실행할 수 없다.

=> 멀티 스레드 환경에서 안전하게 객체 추가/삭제가 가능하다.

//생성 방법
List<E> list = new Vector<E>(); //E타입 객체만 저장
List<E> list = new Vector<>(); //E타입 객체만 저장
List<> list = new Vector<>(); //모든 타입 객체 저장

=>코드에 여러 스레드가 있어 thread1.start(); thread2.start();해도 한 번에 하나의 스레드만 실행시킨다.

 

LinkedList

LinkedList는 ArrayList와 사용 방법은 동일하지만 내부 구조는 완전히 다르다. ArrayList는 배열에 객체를 저장하지만, LinkedList는 인접 객체를 체인처럼 연결해서 관리한다.

- 특정 위치에서 객체를 삽입/삭제하면 바로 앞 뒤 링크만 변경되므로 빈번한 삽입/삭제에서는 ArrayList보다 좋다.

 

//생성 방법
List<E> list = new LinkedList<E>(); //E타입 객체만 저장
List<E> list = new LinkedList<>(); //E타입 객체만 저장
List<> list = new LinkedList<>(); //모든 객체 저장

 

Set 컬렉션

List와 달리 Set은 저장 순서가 유지되지 않는다. 또한 객체를 중복해서 저장할 수 없고, 하나의 null만 저장할 수 있다.

기능 메소드 설명
객체
추가
boolean add(E e) 주어진 객체를 성공적으로 저장하면 true를 리턴하고 중복 객체면 false를 리턴
객체
검색
boolean contains(Object o) 주어진 객체가 저장되어 있는지 여부
isEmpty() 컬렉션이 비어 있는지 조사
Iterator<E> iterator() 저장된 객체를 한 번씩 가져오는 반복자 리턴
int size() 저장된 객체 수 리턴
객체
삭제
void clear() 저장된 모든 객체를 삭제
boolean remove(Object o) 주어진 객체를 삭제

 

HashSet

- Set컬렉션 중 가장 많이 사용되는 것

//생성 방법
Set<E> set = new HashSet<E>(); //E타입 객체만 저장
Set<E> set = new HashSet<>(); //E타입 객체만 저장
Set<> set = new HashSet<>(); //모든 타입 객체 저장

=>HashSet은 hashCode()의 리턴값이 같고 equals()메소드가 true를 리턴하면 동등한 객체로 보고 중복 저장하지 않는다.

 

* Set은 index가 없어 객체를 검색해서 가져오는 방법이 없다. 그래서 2가지 방법을 이용한다.

//Set에서 객체를 가져오는 방법

//1.for문 이용
Set<E> set = new HashSet<>();
for (E e:set){
	...
}

//2.Iterator이용
Set<E> set = new HashSet<>();
Iterator<E> iterator = set.iterator();

 

리턴타입 iterator 메소드명 설명
boolean hasNext() 가져올 객체가 있으면 true, 없으면 false
E next() 컬렉션에서 하나의 객체를 반환
void remove() next()로 가져온 객체를 Set컬렉션에서 제거한다.

 

//사용 방법
while(iterator.hasNext()){
	E e = iterator.next();
}

 

Map 컬렉션

Map 컬렉션은 키(key)와 값(value)으로 구성된 엔트리 객체를 저장한다. 여기서 키와 값은 모두 객체이다.

키 - 중복저장 불가능

값 - 중복저장 가능

기능 메소드 설명
객체 추가 V put(K key, V value) 주어진 키와 값을 추가, 저장되면 값을 리턴
객체 검색 boolean containsKey(Object key) 주어진 키가 있는지 여부
boolean containsValue(Object Value) 주어진 값이 있는지 여부
Set<Map.Entry<K,V>> entrySet() 키,값 쌍으로 구성된 모든 Map.Entry 객체를 Set에 담아서 리턴
V get(Object key) 주어진 키의 값을 리턴
boolean isEmpty() 컬렉션이 비어있는지 여부
Set<K> keySet() 모든 키를 Set객체에 담아 리턴
int size() 저장된 키의 총 수를 리턴
Collection<V> values() 저장된 모든 값 Collection에 담아서 리턴
객체 삭제 void clear() 모든 Map.Entry(키와 값)을 삭제
V remove(Object key) 주어진 키와 일치하는 Map.Entry 삭제.
삭제되면 값을 리턴

 

HashMap

키로 사용할 객체가 hashCode() 메소드의 리턴값이 같고 equals() 메소드가 true를 리턴할 경우, 동일 키로 보고 중복 저장을 허용하지 않는다.

 

//생성 방법
Map<K,V> map = new HashMap<K,V>();
Map<K,V> map = new HashMap<>();

 

Hashtable

Hashtable은 HashMap과 동일한 내부 구조를 갖고 있다. 차이점으로는 Hashtable은 동기화된 메소드로 구성되어 있어 멀티 스레드가 동시에 Hashtable의 메소드들을 실행할 수 없다.

따라서 멀티 스레드 환경에서도 안전하게 객체를 추가, 삭제할 수 있다.

Map<String, Integer> map = new Hashtable<String, Integer>();
Map<String, Integer> map = new Hahtable<>();

 

Properties

Hashtable의 자식 클래스이기 때문에 Hahtable의 특징을 그대로 갖고 있다. Properties는 키와 값을 String으로 제한한 컬렉션이다.

주로 .properties인 프로퍼터 파일을 읽을 때 사용한다.

//database.properties
driver=oracle.jdbc.OracleDirver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=scott
password=tiger
admin=\uD64D\uAE38\uB3D9
Properties properties = new Properties();
properties.load(Xxx.class.getResourceAsStream("database.properties"));

 

검색 기능을 강화시킨 컬렉션

컬렉션 프레임워크는 검색 기능을 강화시킨 TreeSet, TreeMap을 제공한다.

 

TreeSet

- 이진트리를 기반으로 한 Set컬렉션

TreeSet에 객체를 저장할 때는 부모 노드의 객체와 비교해 낮은 것은 왼쪽 자식에, 높은 것은 오른쪽 자식 노드에 저장한다.

//생성 방법
TreeSet<E.=> treeSet = new TreeSet<E>;
TreeSet<E.=> treeSet = new TreeSet<>;

 

TreeMap

이진트리를 기반으로 한 Map 컬렉션. TreeSet과의 차이점은 키와 값이 저장된 Entry를 저장한다는 점이다.

TreeMap에 엔트리를 저장하면 키를 기준으로 자동 정렬되는데 부모 키값보다 낮은건 왼쪽, 큰 건 오른쪽 자식 노드에 Entry객체를 저장한다.

TreeMap<K,V> treeMap = new TreeMap<K,V>();
TreeMap<K,V> treeMap = new TreeMap<>();

 

Comparable과 Comparator

TreeSet에 저장되는 객체와 TreeMap에 저장되는 키 객체는 저장과 동시에 오름차순으로 정렬되는데,

객체가 Comparable 인터페이스를 구현하고 있어야 가능하다. Comparable인터페이스를 받아 compareTo()를 재정의해야한다.

리턴 타입 메소드 설명
int compareTo(T o) 주어진 객체와 같으면 0,
크면 양수,
작으면 음수 리턴

 

Comparable 비구현 객체를 저장하고 싶다면 TreeSet과 TreeMap을 생성할 때 비교자(Comparator)를 제공하면 된다.

TreeSet<E> treeSet = new TreeSet<E>(new ComparatorImpl));

TreeMap<K,V> treeMap = new TreeMap<K,V>(new ComparatorImpl());

 

LIFO와 FIFO 컬렉션

LIFO(Last In First Out): 후입선출 => 스택

FIFO(First in First Out): 선입선출 => 

Stack

//스택 생성 방법
Stack<E> stack = new Stack<E>();
Stack<E> stack = new Stack<>();
리턴 타입 메소드 설명
E push(E item) 주어진 객체를 스택에 넣는다.
E pop() 스택의 맨 위 객체를 빼낸다

 

Queue

//큐 생성 방법
Queue<E> queue = new LinkedList<E>();
Queue<E> queue = new LinkedList<>();
리턴 타입 메소드 설명
boolean offer(E e) 주어진 객체를 큐에 넣는다.
E poll() 큐에서 객체를 빼낸다.

 

728x90
반응형
LIST

'IT > JAVA' 카테고리의 다른 글

[JAVA] #17 스트림 요소 처리  (0) 2023.05.01
[JAVA] #16 람다식  (0) 2023.04.27
[JAVA] #14 멀티 스레드  (0) 2023.04.26
[JAVA] #13 제네릭  (0) 2023.04.24
[JAVA] #12 java.base 모듈  (0) 2023.04.20

+ Recent posts