CREATE TRIGGER trigger_name 
timing[BEFORE|AFTER] event[INSERT|UPDATE|DELETE]
ON table_name
[FOR EACH ROW]
[WHEN conditions]
BEGIN 
statement
END
------ Trigger : 자동실행되는 procedure 이다.
create table emp08 
as 
select employee_id,first_name , job_id
from employees 
where 1=0;

desc emp08;
select * from emp08;

create or replace trigger trigger_01
after insert on emp08 
begin 
    dbms_output.put_line('-------------------------신입사원이 들어옴');
end;
/

create table emp08_backup(
empid number ,
salary number ,
hire_date date
)
create or replace  trigger trigger_02
after insert on emp08
for each row
begin
    insert into emp08_backup values(:new.employee_id,100,sysdate);
end;
/

insert into emp08 values (2,'신한2','IT');
insert into emp08 values (3,'신한4','IT');

delete from emp08 where employee_id=2;

select * from emp08_backup;
select * from emp08;


create or replace  trigger trigger_03
before delete on emp08
for each row
begin
    delete from emp08_backup where empid = :old.employee_id;
end;
/


CREATE TABLE 상품(
상품코드 CHAR(6) PRIMARY KEY,
상품명 VARCHAR2(12) NOT NULL,
제조사 VARCHAR(12),
소비자가격 NUMBER(8),
재고수량 NUMBER DEFAULT 0
);

CREATE TABLE 입고(
입고번호 NUMBER(6) PRIMARY KEY,
상품코드 CHAR(6) REFERENCES 상품(상품코드),
입고일자 DATE DEFAULT SYSDATE,
입고수량 NUMBER(6),
입고단가 NUMBER(8),
입고금액 NUMBER(8)
);

INSERT INTO 상품(상품코드, 상품명, 제조사, 소비자가격)
VALUES('A00001','세탁기', 'LG', 500); 
INSERT INTO 상품(상품코드, 상품명, 제조사, 소비자가격)
VALUES('A00002','컴퓨터', 'LG', 700);
INSERT INTO 상품(상품코드, 상품명, 제조사, 소비자가격)
VALUES('A00003','냉장고', '삼성', 600);
commit;

-- 입고 트리거
CREATE OR REPLACE TRIGGER TRG_04
AFTER INSERT ON 입고
FOR EACH ROW
BEGIN
UPDATE 상품
SET 재고수량 = 재고수량 + :NEW.입고수량
WHERE 상품코드 = :NEW.상품코드;
END;

INSERT INTO 입고(입고번호, 상품코드, 입고수량, 입고단가, 입고금액) 
VALUES(1, 'A00001', 5, 320, 1600);
INSERT INTO 입고(입고번호, 상품코드, 입고수량, 입고단가, 입고금액) 
VALUES(2, 'A00001', 20, 320, 1600);


SELECT * FROM 입고;
SELECT * FROM 상품;

UPDATE EMPLOYEES SET JOB_ID = 'MK_MAN'
WHERE EMPLOYEE_ID =206;

'DB' 카테고리의 다른 글

Mybatis  (0) 2024.12.02
Spring <-> Oracle 연동방법  (0) 2024.11.29
저장 프로시저  (0) 2024.10.28
인덱스(INDEX)  (0) 2024.10.25
Sequence(오라클)  (0) 2024.10.25

프로시저(Procedure)

데이터베이스에 대한 일련의 작업을 정리한 절차를 관계형 데이터베이스 관리 시스템에 저장한 것으로 영구저장모듈(Persistent Storage Module)이라고도 불립니다.

보통 저장 프로시저를 프로시저라고 부르며, 일련의 쿼리를 마치 하나의 함수처럼 실행하기 위한 쿼리의 집합입니다.

---저장 프로시저 만들기-----
create or replace procedure sp_getFirstName(v_empid in employees.employee_id%type,v_fname in employees.first_name%type )

is


begin

    select first_name
    into v_fname
    from employees
    where employee_id = v_empid;
    dbms_output.put_line('직원번호:' || v_empid);
    dbms_output.put_line('직원 fname ' || v_fname);
    

end;
/
desc user_source;
select * from user_source;


------- 직원번호가 들어가면 이름과 급여를 OUT 하기
create or replace procedure sp_emp (v_empid in employees.employee_id%type ,
                                        v_sal out employees.salary%type,
                                           v_fname out employees.first_name%type )
is 
begin 
    select first_name,salary
    into v_fname,v_sal
    from employees 
    where employee_id = v_empid;

end;
/
variable a number;
exec :a :=200;
variable b number;
variable c varchar2(50);


execute sp_emp (200, :b , :c);
print a;
print b;
print c;
-----------------------PL/SQL 로 함수 만들기----------------------------------
SELECT UPPER('oracle'),f_bonus(105)
FROM DUAL;

select employee_id,salary , f_bonus(employee_id) , salary*200
from employees;

--직원 번호가 들어가면 직원급여 * 200 return 한다.
create or replace function f_bonus(v_empid in employees.employee_id%type)
    return number
is
    v_sal employees.salary%type;
begin
    select salary
    into v_sal
    from employees
    where employee_id = v_empid;
    return v_sal*200;
end;
/
----procedure : 미리 컴파일된 프로그램 ,오래걸리는 작업을 수행해야 한다면 자바 application 에서 SQL 문을 DB 에 보내는것보다 빠르다.
----------------직원번호가 들어오면 직원이 근무하는 부서의 이름과 근무도시를 out하는 PROCEDURE 를 작성하시오
create or replace procedure SP_EMP3 (v_empid in employees.employee_id%type, 
                                    v_deptname out departments.department_name%type,
                                    v_city out locations.city%type
)
is
begin 
    select department_name , city
    into v_deptname,v_city
    from  employees 
    join departments using (department_id)
    join locations using(location_id)
    where employee_id = 100;

end;
/   
variable v_empid number;
exec :v_empid: = 105;
variable v_deptname varchar2(50);
variable v_city varchar2(50);

exec SP_EMP3(:v_empid,:v_deptname, :v_city);
print v_empid;
print v_deptname;
print v_city

------------------------직원의 급여는 salary + salary * commission_pct 입니다. 급여를 ㅈ주면 실수령액이 return 되는 function을 작성하시오
create or replace function f_salary(v_empid in employees.employee_id%type)
return number
is
    v_salary employees.salary%type;
begin
    select salary + salary * nvl(commission_pct,0)
    into v_salary
    from employees
    where employee_id = v_empid;
    return v_salary;
end;
/
select employee_id , salary,commission_pct,f_salary(employee_id),lower(first_name)
from employees;

'DB' 카테고리의 다른 글

Spring <-> Oracle 연동방법  (0) 2024.11.29
DB-트리거  (0) 2024.10.28
인덱스(INDEX)  (0) 2024.10.25
Sequence(오라클)  (0) 2024.10.25
TRANSACTION/제약조건/테이블생성시 제약조건  (0) 2024.10.25
public class CRUDController {

	static Scanner sc = new Scanner(System.in);
	static EmpService empservice = new EmpService();

	public static void main(String[] args) {
		boolean isStart = false;
		while (!isStart) {
			menu();
			int job_select = Integer.parseInt(sc.nextLine());
			switch (job_select) {
			case 1 -> {
				f_select();
			}
			case 2 -> {
				f_insert();
			}
			case 3 -> {
				f_update();
			}
			case 4 -> {
				f_delete();
			}
			case 5 -> {
				f_selectByIdService();
			}
			case 6->{
				f_selectByEmpFourService();
			}

			case 7 -> {
				f_selectByDeptService();
			}
			case 8 -> {
				f_selectByJobService();
			}
			case 9 -> {
				f_selectByEmpSalService();
			}
			case 10 -> {
				isStart = true;
			}

			default -> {
				System.out.println("작업선택 오류");
			}

			}
		}
		sc.close();
		System.out.println("====프로그램 종료======");
	}

	private static void f_update() {

		int result = empservice.updateService(f_makeEmp());
		EmpView.display(result + "건 수정");
	}

	private static EmpDTO f_makeEmp() {
		System.out.print("직원번호>>");
		int emp_id = Integer.parseInt(sc.nextLine());

		System.out.println("first_name >>");
		String fname = sc.nextLine();

		System.out.println("Last_name");
		String lname = sc.nextLine();

		System.out.println("이메일");
		String email = sc.nextLine();

		System.out.println("전화번호");
		String phone_number = sc.nextLine();

		System.out.println("hire_date");
		String hdate = sc.nextLine();
		Date hire_date = DateUtil.convertSqlDate(DateUtil.convertDate(hdate));

		System.out.println("job_id");
		String job_id = sc.nextLine();

		System.out.println("salary");
		Double salary = Double.parseDouble(sc.nextLine());

		System.out.println("commission");
		double commission = Double.parseDouble(sc.nextLine());

		System.out.println("mgr_id");
		int mid = Integer.parseInt(sc.nextLine());

		System.out.println("dept_id");
		int dept_id = Integer.parseInt(sc.nextLine());

		EmpDTO emp = new EmpDTO();
		emp.setCommission_pct(commission);
		emp.setDepartment_id(dept_id);
		emp.setEmail(email);
		emp.setEmployee_id(emp_id);
		emp.setFirst_name(fname);
		emp.setLast_name(lname);
		emp.setHire_date(hire_date);
		emp.setJob_id(job_id);
		emp.setManager_id(mid);
		emp.setPhone_number(phone_number);
		emp.setSalary(salary);

		return emp;
	}

	private static void f_insert() {

		empservice.insertService(f_makeEmp());
	}

	private static void f_select() {

		List<EmpDTO> empList = empservice.SelectAllService();
		EmpView.display(empList);

	}

	private static void f_selectByIdService() {
		System.out.println("직원번호>>");
		int empid = Integer.parseInt(sc.nextLine());

		EmpDTO emp = empservice.selectByIdService(empid);
		EmpView.display(emp);

	}

	private static void f_delete() {
		System.out.print("삭제할 직원번호>>");
		int emp_id = Integer.parseInt(sc.nextLine());
		int result = empservice.deleteService(emp_id);
		EmpView.display(result + "건 삭제됨");

	}

	private static void menu() {

		System.out.println("===================================");
		System.out.println("1.조회 2.입력 3.수정 4. 삭제 5.상세보기6.종료");
		System.out.println("===================================");
		System.out.print("작업선택>>>>>>>>>>>>>>");

	}

	private static void f_selectByDeptService() {
		System.out.println("부서번호>>");
		int deptid = Integer.parseInt(sc.nextLine());

		List<EmpDTO> deptList = empservice.selectByDeptId(deptid);
		EmpView.display(deptList);

	}

	private static void f_selectByJobService() {
		System.out.println("직업번호>>");
		String jobid = sc.nextLine();

		List<EmpDTO> jobEmpList = empservice.selectByJobId(jobid);
		EmpView.display(jobEmpList);

	}

	private static void f_selectByEmpSalService() {
		System.out.println("급여조회>>");
		double salary = Integer.parseInt(sc.nextLine());

		List<EmpDTO> deptList = empservice.selectByEmpSalId(salary);
		EmpView.display(deptList);

	}

	private static void f_selectByEmpFourService() {
		// 부서,직책 ,급여,입사일 조건으로 조회
		System.out.println("조회dept)id");
		int deptid = Integer.parseInt(sc.nextLine());

		System.out.println("조회 job_id");
		String job_id = sc.nextLine();

		System.out.println("급여>>");
		double salary = Integer.parseInt(sc.nextLine());

		System.out.print("입사일 hire_date(yyyy-MM-dd) 이상>>");
		String hdate = sc.nextLine();
		Date hire_date = DateUtil.convertSqlDate(
				            DateUtil.convertDate(hdate));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("department_id", deptid);
		map.put("job_id", job_id);
		map.put("salary", salary);
		map.put("hire_date", hire_date);

		List<EmpDTO> deptList = empservice.selectByFour(map);
		EmpView.display(deptList);

	}

}

'Java' 카테고리의 다른 글

Junit  (0) 2024.12.05
LOG4J  (0) 2024.12.03
JDBC-DAO  (0) 2024.10.25
JDBC-DTO  (0) 2024.10.25
JDBC-View  (0) 2024.10.25
package com.shinhan.dbtest;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.firstzone.dept.DeptDto;

//DAO(Data Access Object)
//Service 	---> DB 에 간다 
//			<---
public class EmpDAO {
	String sql_SelectByJob_id = "select * from employees where  JOB_ID =  ?";
	String sql_SelectBy_Salary = "select * from employees where  salary  >= ?";
	String sql_Four_where = """
			
			select * from employees where  department_id = ? and job_id =?  and salary >=  ? and hire_date >=?
			"""  ;
	Connection conn = DBUtil.getConnection();
	PreparedStatement st;
	Statement sta;
	ResultSet rs;
	

	
	/**
	 * 
	 * // 4.부서,직책 ,급여,입사일 조건으로 조회
	// where department_id =? and where job_id =? and where salary >=? and where
	// hire_date >=?
	 * 
	 * @param map
	 * @return
	 */
	
	public List<EmpDTO> selectByFour(Map<String,Object> map) {
		// 특정직원 하기 조회하기
	
		Connection conn = DBUtil.getConnection();
		
	
		List<EmpDTO> empFourList = new ArrayList<EmpDTO>();

		try {
			st = conn.prepareStatement(sql_Four_where);
			//값4개 셋팅 
			//1부서 id
			st.setInt(1,(Integer)map.get("department_id"));
			//2직업id
			st.setString(2,(String)map.get("job_id"));
			//3급여
			st.setDouble(3,(Double)map.get("salary"));
			//4입사날짜
			st.setDate(4,(Date)map.get("hire_date"));
			rs = st.executeQuery();
			while (rs.next()) {
				EmpDTO emp = makeEmp(rs);
				empFourList.add(emp);

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.dbDisconnect(conn, st, rs);
		}

		return empFourList;
	}
	
	
	
	
	/*
	 * 
	 * ? 이상의 급여 직원 찾기
	 * 
	 * 
	 */
	public List<EmpDTO> selectBySalId(double salary) {
		
		Connection conn = DBUtil.getConnection();

		List<EmpDTO> empSalList = new ArrayList<EmpDTO>();

		try {
			st = conn.prepareStatement(sql_SelectBy_Salary);
			st.setDouble(1, salary);
			rs = st.executeQuery();

			while (rs.next()) {
				EmpDTO emp = makeEmp(rs);
				empSalList.add(emp);

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.dbDisconnect(conn, st, rs);
		}

		return empSalList;
	}
	
	
	
	
	/*
	 * 
	 * 
	 * 
	 * 	// 2.특정job_id 인 직원조회 where job_id
	 * 
	 */
	public List<EmpDTO> selectByJobId(String jobid) {
		// 특정직원 하기 조회하기

		List<EmpDTO> jobEmpList = new ArrayList<EmpDTO>();

		try {
			st = conn.prepareStatement(sql_SelectByJob_id);
			st.setString(1, jobid);
			rs = st.executeQuery();

			while (rs.next()) {
				EmpDTO emp = makeEmp(rs);
				jobEmpList.add(emp);

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.dbDisconnect(conn, st, rs);
		}

		return jobEmpList;
	}

	/*
	 * 특정부서의 직원 조회 //1.특정부서의 직원 조회 where department_id List<EmpDTO>
	 */
	public List<EmpDTO> selectByDeptId(int deptid) {
		// 특정직원 하기 조회하기
		String sql = "select * from employees where  department_id =  " + deptid;
		Connection conn = DBUtil.getConnection();
		Statement st = null;
		ResultSet rs = null;
		List<EmpDTO> deptEmpList = new ArrayList<EmpDTO>();

		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);

			while (rs.next()) {
				EmpDTO emp = makeEmp(rs);
				deptEmpList.add(emp);

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.dbDisconnect(conn, st, rs);
		}

		return deptEmpList;
	}

	public List<EmpDTO> selectAll() {

		// 모든직원 조회하기
		String sql = "select * from employees";
		Connection conn = DBUtil.getConnection();
		Statement st = null;
		ResultSet rs = null;
		List<EmpDTO> empList = new ArrayList<EmpDTO>();

		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);

			while (rs.next()) {
				EmpDTO emp = makeEmp(rs);
				empList.add(emp);

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.dbDisconnect(conn, st, rs);
		}
		for (EmpDTO emp : empList) {
			System.out.println(emp);
		}
		return empList;

	}

	private EmpDTO makeEmp2(ResultSet rs) throws SQLException {
		// GET 데이타는 컬럼이기떄문에 대소문자 상관없음
		// 빌더로 간단하게 표현가능
		EmpDTO emp = EmpDTO.builder()
				.commission_pct(rs.getDouble("Commission_pct"))
				.department_id(rs.getInt("Department_id"))
				.email(rs.getString("email"))
				.employee_id(rs.getInt("Employee_id"))
				.first_name(rs.getString("first_name"))
				.last_name(rs.getString("Last_name"))
				.hire_date(rs.getDate("Hire_date"))
				.job_id(rs.getString("job_id"))
				.manager_id(rs.getInt("Manager_id"))
				.phone_number(rs.getString("Phone_number"))
				.salary(rs.getDouble("salary"))
				.build();



		return emp;
	}

	private EmpDTO makeEmp(ResultSet rs) throws SQLException {
		// GET 데이타는 컬럼이기떄문에 대소문자 상관없음
		EmpDTO emp = new EmpDTO();
		emp.setCommission_pct(rs.getDouble("Commission_pct"));
		emp.setDepartment_id(rs.getInt("Department_id"));
		emp.setEmail(rs.getString("Email"));
		emp.setEmployee_id(rs.getInt("Employee_id"));
		emp.setFirst_name(rs.getString("First_name"));
		emp.setLast_name(rs.getString("Last_name"));
		emp.setHire_date(rs.getDate("Hire_date"));
		emp.setJob_id(rs.getString("Job_id"));
		emp.setManager_id(rs.getInt("Manager_id"));
		emp.setPhone_number(rs.getString("Phone_number"));
		emp.setSalary(rs.getDouble("Salary"));

		return emp;
	}

	public EmpDTO selectById(int empid) {
		// 특정직원 하기 조회하기
		String sql = "select * from employees where  employee_id =  " + empid;
		Connection conn = DBUtil.getConnection();
		Statement st = null;
		ResultSet rs = null;
		EmpDTO emp = null;

		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);

			if (rs.next()) {

				emp = makeEmp(rs);

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.dbDisconnect(conn, st, rs);
		}

		return emp;
	}

	public int insert(EmpDTO emp) {
		int result = 0;
		String sql = "insert into employees values (?,?,?,?,?,?,?,?,?,?,?)";
		Connection conn = DBUtil.getConnection();
		try {
			PreparedStatement st = conn.prepareStatement(sql);
			st.setInt(1, emp.getEmployee_id());
			st.setString(2, emp.getFirst_name());
			st.setString(3, emp.getLast_name());
			st.setString(4, emp.getEmail());
			st.setString(5, emp.getPhone_number());
			st.setDate(6, emp.getHire_date());
			st.setString(7, emp.getJob_id());
			st.setDouble(8, emp.getSalary());
			st.setDouble(9, emp.getCommission_pct());
			st.setInt(10, emp.getManager_id());
			st.setInt(11, emp.department_id);

			result = st.executeUpdate();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	public int update(EmpDTO emp) {
		int result = 0;
		String sql = """
				update employees set
				FIRST_NAME =?,
				LAST_NAME=?,
				EMAIL=?,
				PHONE_NUMBER=?,
				HIRE_DATE=?,
				JOB_ID=?,
				SALARY=?,
				COMMISSION_PCT=?,
				MANAGER_ID=?,
				DEPARTMENT_ID=?
				where EMPLOYEE_ID =?
							""";
		Connection conn = DBUtil.getConnection();
		PreparedStatement st = null;

		try {
			st = conn.prepareStatement(sql);

			st.setString(1, emp.getFirst_name());
			st.setString(2, emp.getLast_name());
			st.setString(3, emp.getEmail());
			st.setString(4, emp.getPhone_number());
			st.setDate(5, emp.getHire_date());
			st.setString(6, emp.getJob_id());
			st.setDouble(7, emp.getSalary());
			st.setDouble(8, emp.getCommission_pct());
			st.setInt(9, emp.getManager_id());
			st.setInt(10, emp.getDepartment_id());
			st.setInt(11, emp.getEmployee_id());
			result = st.executeUpdate();

		} catch (Exception e) {
		}

		return result;
	}

	public int delete(int empid) {

		int result = 0;
		String sql = """
				delete from employees
				where EMPLOYEE_ID=?
				""";
		Connection conn = DBUtil.getConnection();
		PreparedStatement st = null;
		try {
			st = conn.prepareStatement(sql);
			st.setInt(1, empid);
			result = st.executeUpdate();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.dbDisconnect(conn, st, null);
		}

		return result;

	}

}

'Java' 카테고리의 다른 글

LOG4J  (0) 2024.12.03
JDBC-Controller  (0) 2024.10.25
JDBC-DTO  (0) 2024.10.25
JDBC-View  (0) 2024.10.25
JDBC-Service  (0) 2024.10.25
//DTO : Data Transfer Object
//VO : Value Object 
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class EmpDTO {

	int employee_id;
	String first_name;
	String last_name;
	String email;
	String phone_number;
	Date hire_date;
	String job_id;
	double salary;
	double commission_pct;
	int manager_id;
	int department_id;
}

'Java' 카테고리의 다른 글

JDBC-Controller  (0) 2024.10.25
JDBC-DAO  (0) 2024.10.25
JDBC-View  (0) 2024.10.25
JDBC-Service  (0) 2024.10.25
자바 상속  (0) 2024.10.04
public class EmpView {

	public static void display(List<EmpDTO> empList) {
		System.out.println("=====모든 직원 조회=====");
		for(EmpDTO emp:empList)
		{
			System.out.println(emp);
		}
		}
	
	public static void display(EmpDTO emp) {
		System.out.println("=====모든 직원 조회=====");
		System.out.println(emp==null? "직원x" : emp);
		}
	
	public static void display(String message){
		System.out.println("[알림]" + message);
	}
}

 

'Java' 카테고리의 다른 글

JDBC-DAO  (0) 2024.10.25
JDBC-DTO  (0) 2024.10.25
JDBC-Service  (0) 2024.10.25
자바 상속  (0) 2024.10.04
자바 CRUD 메모리 저장 방식  (0) 2024.09.26
//사용자요청 --> Controller --> Service --> Dao --> DB
//DB 관련 없는 업무로직은 Service 에서 수행

public class EmpService {

	EmpDAO empDAO = new EmpDAO();
	
	public List<EmpDTO> SelectAllService() {
		
		
		return empDAO.selectAll();
	}

	public EmpDTO selectByIdService(int empid) {
		
		return empDAO.selectById(empid);
		
		
	}
	
	public int insertService(EmpDTO emp) {
		return empDAO.insert(emp);
	}
	
	public int updateService(EmpDTO emp) {
		return empDAO.update(emp);
	}
	
	public int deleteService(int empid) {
		return empDAO.delete(empid);
	}
	public List<EmpDTO> selectByDeptId(int deptid) {
		
		return empDAO.selectByDeptId(deptid);
		
		
	}
public List<EmpDTO> selectByJobId(String jobid) {
		
		return empDAO.selectByJobId(jobid);
		
		
	}
public List<EmpDTO> selectByEmpSalId(double salary) {
	
	return empDAO.selectBySalId(salary);
	
	
}
//여러개의 조건 의경우
public List<EmpDTO> selectByFour(Map<String , Object> empFourList) {
	
	return empDAO.selectByFour(empFourList);
	
	
}
	
}

'Java' 카테고리의 다른 글

JDBC-DAO  (0) 2024.10.25
JDBC-DTO  (0) 2024.10.25
JDBC-View  (0) 2024.10.25
자바 상속  (0) 2024.10.04
자바 CRUD 메모리 저장 방식  (0) 2024.09.26

index : 검색속도 향상을 위함 , primary , key , unique 설정하면 자동으로 만들어진다.

 

인덱스 생성

CREATE TABLE EMP01
AS
SELECT * FROM EMP;

 

인덱스 설정 확인

SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME 
FROM USER_IND_COLUMNS
WHERE TABLE_NAME IN('EMP', 'EMP01');

'DB' 카테고리의 다른 글

DB-트리거  (0) 2024.10.28
저장 프로시저  (0) 2024.10.28
Sequence(오라클)  (0) 2024.10.25
TRANSACTION/제약조건/테이블생성시 제약조건  (0) 2024.10.25
executeQuery와 executeUpdate()의 차이  (0) 2024.10.25

--Primary Key : not null  , unique , 의미 있는 번호는 프로그램또는 사용자의 입력으로 키를 만든다.
--키가 중요한 의미가 아니면 번호 자동발생기를 이용 (Oracle은 Sequence) , (mysql autoincrement)

시퀀스 생성

 

CREATE SEQUENCE sequence_name 
                [START WITH n]              ① 
                [INCREMENT BY n]            ② 
                [{MAXVALUE n | NOMAXVALUE}] ③
                [{MINVALUE n | NOMINVALUE}] ④
                [{CYCLE | NOCYCLE}]         ⑤
                [{CACHE n | NOCACHE}]

 

시퀀스 수정 

 

ALTER SEQUENCE sequence_name 
[INCREMENT BY n] 
[{MAXVALUE n | NOMAXVALUE}] 
[{MINVALUE n | NOMINVALUE}] 
[{CYCLE | NOCYCLE}] 
[{CACHE n | NOCACHE}]

 

 

'DB' 카테고리의 다른 글

DB-트리거  (0) 2024.10.28
저장 프로시저  (0) 2024.10.28
인덱스(INDEX)  (0) 2024.10.25
TRANSACTION/제약조건/테이블생성시 제약조건  (0) 2024.10.25
executeQuery와 executeUpdate()의 차이  (0) 2024.10.25

<DDL>

CREATE TABLE , DROP TABLE,REANME

<DML>

INSERT , DELETE , UPDATE

<TRANSACTION>

: 하나의 논리적인 작업단위(COMMIT,ROLLBACK)

제약조건
constraint_type : C(check, not null은 필수) , U(unique) , R(reference) , p(primary = notnull + unique)
desc user_constraints;
SELECT * FROM user_constraints
where table_name ='EMPLOYEES';

 

CONSTRAINT EMP06_DEPTNO_FK REFERENCES DEPARTMENTS(DEPARTMENT_ID)-->DEPARTMENTS 테이블을 부모테이블로 참조 함

테이블 생성시 제약 조건

---회원가입 (tbl_member)
---회원번호 숫자 (PK)
---회원이름 문자 (NOT NULL)
---회원이메일 문자 NULL 허용 UNIQUE
---회원월급 수입 (500~1000)
---회원성별 (남자,여자)
---담당부서 (DEPARTMENTS 참조)
CREATE TABLE MEMBER(
MEMBER_NO NUMBER(4) CONSTRAINT MEMBER_NO_PK PRIMARY KEY,
MEMBER_NAME VARCHAR2(30) NOT NULL,
MEMBER_EMAIL VARCHAR2(30) UNIQUE,
MEMBER_MON_SAL NUMBER(10) CONSTRAINT MEMBER_SAL_CK CHECK(MEMBER_MON_SAL BETWEEN 500 AND 1000),--제약조건 500~ 1000 사이
MEMBER_GENDER VARCHAR2(2) CONSTRAINT MEMBER_GEN_CK CHECK (MEMBER_GENDER IN('M', 'F')),--- M 과 F 만됨
MEMBER_DEPARTMENT NUMBER(5) 
CONSTRAINT MEMBER_DEPART_KEY REFERENCES DEPARTMENTS(DEPARTMENT_ID)-->DEPARTMENTS 테이블을 부모테이블로 참조 함
);

 

---복합키(여러칼람의 조합으로 유일성을 보장)----

---고객정보(고객번호키) , 상품정보(상품번호키) , 주문(고객번호키+상품번호키 + 날짜+seq , 너무 복잡하면 추카키 만든다)(주문번호)

CREATE TABLE MEMBER01( 
NAME VARCHAR2(10),
ADDRESS VARCHAR2(30),
HPHONE VARCHAR2(16),
CONSTRAINT MEMBER01_COMBO_PK PRIMARY KEY(NAME, HPHONE) ---두개의 키 조합 하나만 중복 되도 가능
);

 

 

--기존테이블 제약조건 추가하기 

ALTER TABLE table_name 
ADD [CONSTRAINT constraint_name] 
constraint_type (column_name);

 

제약조건 제거

ALTER TABLE table_name 
DROP [CONSTRAINT constraint_name];

 

제약조건 비활성화

DISABLE CONSTRAINT : 제약 조건의 일시 비활성화

ENABLE CONSTRAINT : 비활성화된 제약 조건을 해제하여 다시 활성화

ALTER TABLE table_name 
DISABLE [CONSTRAINT constraint_name];

 

 

'DB' 카테고리의 다른 글

DB-트리거  (0) 2024.10.28
저장 프로시저  (0) 2024.10.28
인덱스(INDEX)  (0) 2024.10.25
Sequence(오라클)  (0) 2024.10.25
executeQuery와 executeUpdate()의 차이  (0) 2024.10.25

+ Recent posts