📙 STUDENT 테이블 만들기
: 학번(숫자형-PRIMARY KEY),이름(문자형),전화번호(문자형),주소(문자형),생년월일(날짜형)
CREATE TABLE STUDENT(NO NUMBER(4) PRIMARY KEY,NAME VARCHAR2(50),PHONE VARCHAR2(20), ADDRESS VARCHAR2(100),BIRTHDAY DATE)
STUDENT 테이블에 학생정보를 삽입하는 JDBC 프로그램 작성
➰ JDBC 관련 객체를 저장하기 위한 참조변수는 try 영역 외부에서 선언
➰ try 영역을 포함한 모든 영역에서 참조변수를 이용해 객체 사용 가능
public class InsertStudentApp {
public static void main(String[] args) {
Connection con=null;
Statement stmt=null;
➰ JDBC Driver : DriverManager 클래스에 등록된 다수의 Driver 객체
➰ Driver 객체 : DBMS 서버에 접속하여 SQL 명령을 전달하기 위한 기능을 제공하는 객체
: Driver 객체를 관리하기 위한 기능을 제공하는 클래스
: Driver 객체를 전달받아 DriverManager 클래스가 관리할 수 있는 JDBC Driver로 등록하는 메소드**
DriverManager.registerDriver(new OracleDriver());
: 메소드를 호출하여 ClassLoader 프로그램을 수동으로 실행하여 OracleDriver 클래스를 읽어 메모리에 저장
Class.forName("oracle.jdbc.driver.OracleDriver");
➰ Connection 객체를 반환받아 저장
➰ Connection 객체 : DBMS 서버에 접속된 정보를 저장하기 위한 객체
DriverManager.getConnection(String url,String username,String password)
> DriverManager 클래스에 등록된 JDBC Driver 객체를 사용하여 DBMS 서버에 접속하는 메소드
> 접속된 DBMS 서버의 정보가 저장된 Connection 객체 반환
Protocol:ServerName:Port:Resource >> ex) http://www.itwill.xyz:80/test/index.html
jdbc:oracle:thin:@ServerName:Port:SID
try {
String url="jdbc:oracle:thin:@localhost:1521:xe";
String username="scott";
String password="tiger";
con=DriverManager.getConnection(url, username, password);
: SQL 명령을 전달할 수 있는 Statement 객체를 생성하여 반환하는 메소드
➰ Statement 객체 : SQL 명령을 접속 DBMS 서버에 전달하여 실행하기 위한 객체
stmt=con.createStatement();
: DML 명령 또는 DDL 명령을 전달하여 실행하기 위한 메소드 - 실행결과로 조작행의 갯수를 정수값(int)으로 반환
: SELECT 명령을 전달하여 실행하기 위한 메소드
: 실행결과로 검색행이 저장된 ResultSet 객체 반환
//String sql="insert into student values(1000,'홍길동','010-1324-7512','서울시 강남구','00/01/01')";
//String sql="insert into student values(2000,'임꺽정','010-4561-7864','수원시 월정구','02/05/08')";
String sql="insert into student values(3000,'전우치','017-8741-2130','인천시 상당구','1998-12-11')";
int rows=stmt.executeUpdate(sql);
: JDBC 기능을 메소드로 작성할 경우 실행에 대한 결과값 반환
System.out.println("[메세지]"+rows+"명의 학생정보를 삽입 하였습니다.");
} catch (ClassNotFoundException e) {
System.out.println("[에러]OracleDriver 클래스를 찾을 수 없습니다.");
} catch (SQLException e) {
System.out.println("[에러]JDBC 관련 오류 = "+e.getMessage());
} finally {//예외와 상관없이 무조건 실행될 명령을 작성하는 영역
//6.JDBC 관련 객체의 close() 메소드를 호출하여 객체 제거
// => JDBC 관련 객체 생성의 반대 순서로 제거
try {
//if 구문을 이용하여 참조변수에 객체가 저장되어 있는 경우에만 close()
//메소드 호출 - NullPointerExcetion 발생 방지
//NullPointerExcetion : 참조변수에 null이 저장된 상태에서 메소드를 호출한 경우 발생되는 예외
if(stmt!=null) stmt.close();//Statement.close() : Statement 객체 제거
//Connection.close() : Connection 객체 제거 - DBMS 서버 접속 종료
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//STUDENT 테이블에 저장된 학생정보 중 학번이 [2000]인 학생의 이름을 [임걱정]으로 변경하고
//주소를 [부천시 원미구]로 변경하는 JDBC 프로그램 작성
public class UpdateStudentApp {
public static void main(String[] args) {
Connection con=null;
Statement stmt=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:xe";
String username="scott";
String password="tiger";
con=DriverManager.getConnection(url, username, password);
stmt=con.createStatement();
String sql="update student set name='임걱정',address='부천시 원미구' where no=2000";
int rows=stmt.executeUpdate(sql);
System.out.println("[메세지]"+rows+"명의 학생정보를 변경 하였습니다.");
} catch (ClassNotFoundException e) {
System.out.println("[에러]OracleDriver 클래스를 찾을 수 없습니다.");
} catch (SQLException e) {
System.out.println("[에러]JDBC 관련 오류 = "+e.getMessage());
} finally {
try {
if(stmt!=null) stmt.close();
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
STUDENT 테이블에 학생정보를 검색& 출력하는 JDBC 프로그램 작성
public class SelectStudentApp { public static void main(String[] args) { Connection con=null; Statement stmt=null; ResultSet rs=null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); String url="jdbc:oracle:thin:@localhost:1521:xe"; String username="scott"; String password="tiger"; con=DriverManager.getConnection(url, username, password); stmt=con.createStatement(); String sql="select * from student order by no"; ```
💡 Insert, delete, upadate 는 Statement.executeUpdate(String sql) 메소드 사용
➰ SELECT 명령의 실행결과를 ResultSet 객체로 반환
➰ ResultSet 객체 : 검색결과를 테이블 형식(2차원 배열)의 객체로 저장하여 표현한 객체
rs=stmt.executeQuery(sql);
➰ ResultSet 객체에 저장된 검색행을 행단위로 처리하기 위해 내부적인 커서(Cursor) 제공
ResultSet 커서를 다음행으로 이동하는 메소드 - boolean 반환
- false 반환 : ResultSet 커서 위치에 처리행이 없는 경우의 반환값 - EOF(End Of File)
- true 반환 :ResultSet 커서 위치에 처리행이 있는 경우의 반환값
if(rs.next()) {
//ResultSet 커서를 다음행으로 이동하여 처리행이 존재하는 경우 - 검색행 존재
//System.out.println("[메세지]검색된 학생정보가 있습니다.");
//검색된 다수의 학생정보가 저장된 ResultSet 객체를 처리하기 위한 반복문
// => ResultSet 객체에 저장된 학생정보의 갯수가 불확실하므로 while 반복문 사용
// => 첫번째 행 처리 후 ResultSet 커서를 다음행으로 이동하기 위해 do~while 반복문 사용
do {
- columnIndex : 검색행에서 검색대상의 첨자(Index:1부터 1씩 증가되는 정수값)로 컬럼값 표현
- columnLabel : 검색행에서 검색대상의 이름(컬럼명 또는 별칭)으로 컬럼값 표현
int no=rs.getInt(1);
int no=rs.getInt("no");
String name=rs.getString("name");
String phone=rs.getString("phone");
String address=rs.getString("address");
//Date birthday=rs.getDate("birthday");
//처리행의 컬럼값은 오라클 자료형에 상관없이 getString() 메소드를 호출하여
//문자열(String 객체)로 반환 가능
String birthday=rs.getString("birthday");
System.out.println("학번 = "+no);
System.out.println("이름 = "+name);
System.out.println("전화번호 = "+phone);
System.out.println("주소 = "+address);
//System.out.println("생년월일 = "+birthday);
System.out.println("생년월일 = "+birthday.substring(0,10));
System.out.println("==================================================");
} while(rs.next());//ResultSet 커서 위치에 처리행이 있는 경우 반복문 실행
} else {//ResultSet 커서를 다음행으로 이동하여 처리행이 존재하지 않는 경우 - 검색행 미존재
System.out.println("[메세지]검색된 학생정보가 없습니다.");
}
} catch (ClassNotFoundException e) {
System.out.println("[에러]OracleDriver 클래스를 찾을 수 없습니다.");
} catch (SQLException e) {
System.out.println("[에러]JDBC 관련 오류 = "+e.getMessage());
} finally {
try {
if(rs!=null) rs.close();
if(stmt!=null) stmt.close();
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
➰ JDBC 프로그램은 기본적으로 AutoCommit 기능이 활성화 처리되어 있어 SQL 명령(DML)이 전달되어 실행되면 자동으로 커밋 처리
: AutoCommit 기능의 사용여부를 변경하는 메소드
con.setAutoCommit(false);
//STUDENT 테이블에 저장된 학생정보 중 학번이 [2000]인 학생의 이름을 [임꺽정]으로 변경하는 JDBC 프로그램 작성
public class TransactionControlApp {
public static void main(String[] args) {
Connection con=null;
Statement stmt=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:xe";
String username="scott";
String password="tiger";
con=DriverManager.getConnection(url, username, password);
//Connection.setAutoCommit(boolean autoCommit) : AutoCommit 기능의 사용여부를 변경하는 메소드
// => false : AutoCommit 기능 비활성화, true : AutoCommit 기능 활성화(기본)
con.setAutoCommit(false);
stmt=con.createStatement();
String sql="update student set name='임꺽정' where no=2000";
int rows=stmt.executeUpdate(sql);
//if(con!=null) throw new Exception();//무조건 예외 발생
if(rows>0) {//조작된 행이 있는 경우
System.out.println("[메세지]"+rows+"명의 학생정보를 변경 하였습니다.");
} else {//조작된 행이 없는 경우
System.out.println("[메세지]해당 학번의 학생정보를 찾을 수 없습니다.");
}
//Connection.commit() : Connection 객체에 의해 전달된 모든 SQL 명령에 대한 커밋 처리 메소드
con.commit();
} catch (ClassNotFoundException e) {
System.out.println("[에러]OracleDriver 클래스를 찾을 수 없습니다.");
} catch (SQLException e) {
System.out.println("[에러]JDBC 관련 오류 = "+e.getMessage());
} catch (Exception e) {
System.out.println("[에러]프로그램에 예기치 못한 오류가 발생 하였습니다.");
try {
//Connection.rollback() : Connection 객체에 의해 전달된 모든 SQL 명령에 대한 롤백 처리 메소드
con.rollback();
} catch (SQLException e1) { }
} finally {
try {
if(stmt!=null) stmt.close();
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}