Database-DML

 

DML

DDL(데이터 정의어) : create , alter , drop , truncate (rename , modify)
DML(데이터 조작어) : insert, update, delete
DQL(데이터 질의어) : select
DCL(데이터 제어어) : 권한 (암호 바꾸기)(grant , revoke)
TCL(트랜잭션) : commit , rollback , savepoint(특정지점까지 돌아가는 것)
/*
app(java)  ->> jdbc ->> db(oracle)
CRUD 개발자가 하는 작업
--create : insert
--read : select (전체 조회, 조건 조회)
--update : update
--delete : delete
(create,update,delete ) transaction을 동반(commit, rollback)
--함수 최소 5개를 만드는 것 --> JDBC
--public List<Emp> getEmpList(){안에 쿼리문 select*from emp}
--public Emp getEmpListByEmpno(int empno){select... 쿼리문}
--public int insertEmp(Emp emp){insert into emo(....)}
*/

Insert

--DML 작업
--트랜잭션(transaction) : 하나의 논리적인 작업 단위
--은행업무의 출금업무(A라는 계좌에서 돈을 출금에서 B계좌의 이체까지) : 결과는 [성공 or 실패]
--commit[A~B 예외없이 실행되면], rollback[A~ B 예외가 생기면 처음으로 돌아간다.]
/*
 A라는 계좌에서 100만원 출금 >> update
 B라는 계좌에 100만원 입금 >> update
 두가지 update가 실행되면 commit , 하나라도 실패하면 rollback
*/

-- 시스템 사전 정보 쿼리들
desc emp;
--system table 통해서 다양한 정보 제공
select * from tab; -- 현재 접속한 접속계정 (각 계정이 볼수 있는 table)
select * from tab where TNAME = 'BOARD'; -- 테이블 생성 전에 그 정보를 확인
select * from col; -- 사용자가 관리하는 모든 컬럼의 정보
select * from col where tname = 'EMP'; -- 대문자로 써야한다. 특정 테이블이 가지는 컬럼 정보
select *from user_tables; -- 관리자 , 튜닝하는 사람들이 보는 것이다 아주 상세한 정보
select*from user_tables where table_name = 'DEPT'; --시스템 내부 정보를 컬럼으로 검색하는 것

/*
INSERT INTO table_name [(column1[, column2, . . . . . ])] 
VALUES  (value1[, value2, . . . . . . ]); 
*/
create table temp(
  id number primary key , --id 컬럼에 null , 중복값이 안들어간다. , 유일한 데이터 1건을 보장한다.: where id = 10이라고 입력하면 무조건 한 건만 나온다. ex)주민번호
  name varchar2(20) -- default로 null 허용한다.
  );
  
-- 1.가장 일반적인 insert
insert into temp(id,name)
values(100,'홍길동');

select *from temp;
commit; --실 반영하고 싶을 때 백업 안해놓으면 복원 할 수 없다.

-- 2.컬럼 리스트 생략 insert (temp(id,name) >>에서 (id,name) 생략 >>temp 모든 조건 삽입해야한다.
insert into temp --컬럼 리스트 생략 할 수 있지만 되도록이면 쓰자. 가독성을 위해서
values(200,'김유신');
commit;

insert into temp(id,name) -->>id는 기본 키로 설정 되어 있어서 중복 값은 들어갈 수 없다. unique constraint (BITUSER.SYS_C007004) violated , 무결성
values(100,'아무개');          -->> X

insert into temp(name) -->> id는 기본키로 설정 되어 있어서 null값 들어갈 수 없다. cannot insert NULL into ("BITUSER"."TEMP"."ID")
values('아무개'); --> X

--insert 데이터 어느정도 
--일반 SQL은 제어문이 없다.
-- PL SQL은 제어문이 있다. ( for 문을 돌려서 정보를 넣을 수 있다.)
-- 무조건 블록 실행을 해야한다. 넣고 나서 주석을 만들어야 편하다. 안하면 계속 실행
/*
create table temp2(id varchar2(20));
BEGIN
  FOR i IN 1..1000 LOOP
      INSERT INTO temp2(id) VALUES ('A' || to_char(i));
    END LOOP;
  END;
  */
select * from temp2;

create table temp3(
 memberid number(3) not null,
 name varchar2(10), --null 허용
 regdate date default sysdate -- 기본값 설정하기 (insert하지 않으면 기본값으로 서버 날짜 적용) >>ex)회원가입 할때
 );
select sysdate from dual;
insert into temp3(MEMBERID,NAME,regdate)
 values(100,'홍길동','2018-03-02');
select * from temp3;
 --특정 컬럼에 데이터 넣기
insert into temp3(memberid,name)
 values(200,'아무개'); -----default 가 동작해서 regdate컬럼에 >>sysdate값이 자동으로 들어간다.
commit;
 
insert into temp3(memberid)
 values(300);
commit;

-- TIP 1)대량 데이터 insert하기 테이블이 있을때 ,  select 구문(values 구문 대신에)
create table temp4(id number);
create table temp5(num number);
insert into temp4(id) values(1);
insert into temp4(id) values(2);
insert into temp4(id) values(3);
insert into temp4(id) values(4);
insert into temp4(id) values(5);
insert into temp4(id) values(6);
insert into temp4(id) values(7);
insert into temp4(id) values(8);
insert into temp4(id) values(9);
insert into temp4(id) values(10);
commit;
select *from temp4;
--temp4테이블에 있는 모든 데이터를 temp5에 넣고 싶다.
--insert into 테이블명 (컬럼리스트) select 구문(values 구문 대신에)
--단 컬럼의 갯수와 타입이 일치하면
insert into temp5(num) 
select id from temp4;
select *from temp5;
commit;

-- TIP 2)대량 데이터 insert하기 테이블 없을 때
-- as select 복사 컬럼 from 복사할 테이블 where 제약조건
--테이블을 자동으로 생성하고 대량 데이터 삽입
--단 제약 정보는 copy가 안된다.(primery key , foreign key)
--emp table과 같은 구조를 가지고 같은 데이터를 갖는 실습테이블을 만들고 싶다.
create table copyemp
as 
select*from emp;
select*from copyemp;

create table copyemp2
as
select empno, ename , job, sal from emp where deptno = 30;
select*from copyemp2;

--Quiz
--구조만 복사하고 데이터는 복사하고 싶지 않을 때? where에 무조건 거짓인 명제를 넣어준다.
create table copyemp3
as
select * from emp where 1=2;
select * from copyemp3;
--  >> 주의 사항(단점) ,시스템 테이블 사용( 제약 정보 확인하기) 

select*from user_constraints where table_name = 'EMP';
select*from user_constraints where table_name = 'COPYEMP';

create table pktest(id number primary key); --제약조건
insert into pktest(id) values(100);
commit;

create table pktest2
as
select*from pktest;

select*from pktest2;
select*from user_constraints where table_name = 'PKTEST';
select*from user_constraints where table_name = 'PKTEST2'; --제약 조건은 복사되지 않는다.

Update

-- [ UPDATE START]
/*
UPDATE  table_name 
SET  column1 = value1 [,column2 = value2, . . . . . . .] 
[WHERE  condition]; 

UPDATE  table_name 
SET  (column1, column2, . . . . ) =       ( SELECT  column1,column2, . . .     FROM   table_name    WHERE  coundition)   -- subquary
[WHERE  condition]; 
*/
commit;
select* from copyemp;

update copyemp
set sal = 0;

rollback; -- 이전에 commit 한 것 전까지 rollback 된다. ( insert, update , delete에 대해서만)

update copyemp
set job = 'NOT.....'
where deptno = 20;
select * from copyemp order by deptno;
rollback;

--update (subquery와 같이 사용 많이 한다.) 
update copyemp
set sal = (select sum(sal) from copyemp);
rollback;

update copyemp
set ename = 'AAA',job = 'BBB' , hiredate = sysdate
where deptno = 10;
select * from copyemp order by deptno;

Delete

delete from copyemp;
select * from copyemp;
rollback;

delete from copyemp where deptno = 20;
 --delete table( 기존 table의 data를 삭제한다.) >>데이터를 삭제해도 table의 공간을 줄이지 않는다.
 --truncate table( 기존 table의 data와 공간을 삭제한다.) >>데이터를 삭제하면서 공간도 줄인다 , where 조건을 사용 못한다.