선언부 생성
create or replace
package employee_pkg as
procedure print_ename(p_empno number);
procedure print_sal(p_empno number);
end employee_pkg;
본문 생성
create or replace
package body employee_pkg as
procedure print_ename(p_empno number)
is
l_ename emp.ename%type;
begin
SELECT ename INTO l_ename
FROM emp WHERE empno=p_empno;
dbms_output.put_line(l_ename);
end print_ename;
procedure print_sal(p_empno number)
is
l_sal emp.sal%type;
begin
SELECT sal INTO l_sal
FROM emp WHERE empno=p_empno;
dbms_output.put_line(l_sal);
end print_sal;
end employee_pkg;
exec employee_pkg.print_ename(7369);
exec employee_pkg.print_Sal(7369);
트리거 형식
CREATE OR REPLACE TRIGGER 트리거 이름
TIMING[before|after] even [insert|update|delete] on 테이블 이름 --'|'는 또는의 개념
begin
end;
트리거 생성
create or replace trigger print_message
after insert on dept
begin
dbms_output.put_line('DEPT 테이블에 정상적으로 데이터가 추가되었습니다.');
end;
트리거를 생성한 후 DEPT 테이블에 데이터를 추가하면 등록된 트리거가 동작하면서 'DEPT 테이블에 정상적으로 데이터가 추가되었습니다.'를 출력함
INSERT INTO dept VALUES (70,'EDUCATION','BUSAN');
COMMIT;
이제 이클립스 환경에서 DB와 연결할 것이다.
JDK-17버전으로 변경
ojdbc8.jar 파일 설치 후 libs 폴더에 추가
프로젝트 우클릭 -> build path -> 마지막 -> edit해서 17변경 + java complier -> 17로 변경
Add JARs -> ojdbc.jar 추가(자바에서 오라클 적용)
sql파일은 만들어두고 코드 보관, 복사해서 sql developer에서 적용
public class DriverMain {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("오라클 드라이버가 정상적으로 로드되었습니다.");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} // main
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionMain {
public static void main(String[] args) {
String db_driver = "oracle.jdbc.OracleDriver";
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_id = "user01";
String db_password = "1234";
try {
Class.forName(db_driver);
Connection conn = DriverManager.getConnection(db_url,db_id,db_password);
System.out.println("Connection 객체가 생성되었습니다.");
} catch(SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
main 함수
try {
} catch { (예외처리)
} finally{
}
Statement문제
public class CreateTable {
public static void main(String[] args) {
String db_driver = "oracle.jdbc.OracleDriver";
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_id = "user01";
String db_password = "1234";
Connection conn = null;
Statement stmt = null;
String sql = null;
try {
// JDBC 수행 1단계 : 드라이버 로드
Class.forName(db_driver);
// JDBC 수행 2단계 : Connection 객체 생성(오라클 접속을 위한 인증)
conn = DriverManager.getConnection(db_url,db_id,db_password);
System.out.println("test1 테이블을 생성합니다.");
/*
테이블을 생성하는 SQL문 작성.
접속한 계정에 테이블명이 중복되면 에러가 발생하기 때문에 동일한 계정에서는 한번만 수행함
*/
// SQL문 작성
sql = "create table test1 (id varchar2(10),age number(3))";
// JDBC 수행 3단계 : Statement 객체 생성
stmt = conn.createStatement();
// JDBC 수행 4단계 : SQL문 실행
stmt.execute(sql);
System.out.println("테이블이 정상적으로 생성되었습니다.");
} catch(SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// JDBC 수행 5단계 : 자원정리
if(stmt!=null)try {stmt.close();}catch(SQLException e) {}
if(conn!=null)try {conn.close();}catch(SQLException e) {}
// 줄바꿈하면 너무 길어져서 한줄로 처리
}
} // main
} // class
public class InsertTest {
public static void main(String[] args) {
String db_driver = "oracle.jdbc.OracleDriver";
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_id = "user01";
String db_password = "1234";
Connection conn = null;
Statement stmt = null;
String sql = null;
try {
// JDBC 수행 1단계 : 드라이버 로드
Class.forName(db_driver);
// JDBC 수행 2단계 : Connection 객체 생성(오라클 접속 인증)
conn = DriverManager.getConnection(db_url,db_id,db_password);
// SQL문 작성
sql = "INSERT INTO test1 (id,age) VALUES ('s''t',10)";
// JDBC 수행 3단계 : Statement 객체 생성
stmt = conn.createStatement();
// JDBC 수행 4단계 : SQL문을 실행해서 하나의 행을 삽입
// 삽입 작업 후 삽입한 행의 갯수를 반환
int count = stmt.executeUpdate(sql);
System.out.println(count+"개의 행을 추가했습니다.");
} catch (Exception e) {
e.printStackTrace();
} finally {
// JDBC 수행 5단계 : 자원정리
if(stmt!=null) try {stmt.close();} catch (SQLException e) {}
if(conn!=null) try {conn.close();} catch (SQLException e) {}
// 열린 역순으로 닫음
}
} // main
} // class
public class SelectTest {
public static void main(String[] args) {
/*
데이터베이스 작업
C create -> INSERT문
R read -> SELECT문
U update -> UPDATE문
D delete -> DELETE문
*/
String db_driver = "oracle.jdbc.OracleDriver";
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_id = "user01";
String db_password = "1234";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = null;
try {
// JDBC 수행 1단계 : 드라이버 로드
Class.forName(db_driver);
// JDBC 수행 2단계 : Connection 객체 생성(오라클 접속 인증)
conn = DriverManager.getConnection(db_url,db_id,db_password);
// SQL문 작성
sql = "SELECT * FROM test1";
// JDBC 수행 3단계 : Statement 객체 생성
stmt = conn.createStatement();
// JDBC 수행 4단계 : SQL문을 실행해서 테이블로부터
레코드를(복수) 전달받아서 ResultSet 객체에 담아서 반환
rs = stmt.executeQuery(sql);
System.out.println("ID\t나이");
//ResultSet에 보관된 결과집합에 접근해서 행단위로 데이터를 추출
while (rs.next()) {
// 컬럼명을 통해서 데이터를 반환
// System.out.print(rs.getString("id"));
// System.out.print("\t"); //아이디 명시 후 간격 띄움
// System.out.println(rs.getInt("age"));
// 컬럼 인덱스를 통해서 데이터를 반환
System.out.print(rs.getString(1)); // id
System.out.print("\t");
System.out.println(rs.getInt(2)); // age
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// JDBC 수행 5단계 : 자원정리
if(rs!=null)try {rs.close();}catch(SQLException e) {}
if(stmt!=null)try {stmt.close();}catch(SQLException e) {}
if(conn!=null)try {conn.close();}catch(SQLException e) {}
}
} // main
} // class
public class UpdateTest {
public static void main(String[] args) {
String db_driver = "oracle.jdbc.OracleDriver";
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_id = "user01";
String db_password = "1234";
Connection conn = null;
Statement stmt = null;
String sql = null;
try {
// JDBC 수행 1단계 : 드라이버 로드
Class.forName(db_driver);
// JDBC 수행 2단계 : Connection 객체 생성(오라클 접속 인증)
conn = DriverManager.getConnection(db_url,db_id,db_password);
// SQL문 작성
sql = "UPDATE test1 SET age=90 WHERE id='SKY'";
// JDBC 수행 3단계 : Statement 객체 생성
stmt = conn.createStatement();
// JDBC 수행 4단계 : SQL문 실행
// update문을 실행해서 테이블의 행을 수정하고 수정한 행의 개수를 반환
int count = stmt.executeUpdate(sql);
System.out.println(count + "개 행의 정보를 수정했습니다.");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(stmt!=null)try {stmt.close();}catch(SQLException e) {}
if(conn!=null)try {conn.close();}catch(SQLException e) {}
}
} // main
} // class
public class DeleteTest {
public static void main(String[] args) {
String db_driver = "oracle.jdbc.OracleDriver";
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_id = "user01";
String db_password = "1234";
Connection conn = null;
Statement stmt = null;
String sql = null;
try {
// JDBC 수행 1단계 : 드라이버 로드
Class.forName(db_driver);
// JDBC 수행 2단계 : Connection 객체 생성(오라클 접속 인증)
conn = DriverManager.getConnection(db_url,db_id,db_password);
// SQL문 작성
sql = "DELETE FROM test1 WHERE id='SKY'"; // 입력한 대소문자에 맞게 입력
// JDBC 수행 3단계 : Statement 객체 생성
stmt = conn.createStatement();
// JDBC 수행 4단계 : SQL문을 실행해서 테이블의 행을 삭제한 후 삭제한 행의 개수 반환
int count = stmt.executeUpdate(sql);
System.out.println(count + "개 행을 삭제했습니다.");
} catch(Exception e) {
e.printStackTrace();
} finally {
// JDBC 수행 5단계 : 자원정리
if(stmt!=null)try {stmt.close();} catch(SQLException e) {}
if(conn!=null)try {conn.close();} catch(SQLException e) {}
}
} // main
} // class
public class DropTable {
public static void main(String[] args) {
String db_driver = "oracle.jdbc.OracleDriver";
String db_url = "jdbc:oracle:thin:@localhost:1521:xe";
String db_id = "user01";
String db_password = "1234";
Connection conn = null;
Statement stmt = null;
String sql = null;
try {
// JDBC 수행 1단계 : 드라이버 로드
Class.forName(db_driver);
// JDBC 수행 2단계 : Connection 객체 생성(오라클 접속 인증)
conn = DriverManager.getConnection(db_url,db_id,db_password);
System.out.println("test1 테이블을 제거합니다.");
// SQL문 작성
sql = "DROP TABLE test1";
// JDBC 수행 3단계 : Statement 객체 생성
stmt = conn.createStatement();
// JDBC 수행 4단계 : SQL문 실행
System.out.println("테이블이 삭제되었습니다."); // DDL은 0반환, DML일때만 count 사용
} catch(Exception e) {
e.printStackTrace();
} finally {
// JDBC 수행 5단계 : 자원정리
if(stmt!=null)try {stmt.close();}catch(SQLException e) {}
if(conn!=null)try {conn.close();}catch(SQLException e) {}
}
} // main
} // class
ctrl+shift+x : 선택한 부분 대문자
ctrl+shift+y : 선택한 부분 소문자