반응형

Java를 통해서 오라클 DB를 연결한 뒤에 

preparedstatement를 이용하여 create, insert, update, delete를 해보겠습니다.

 

Create

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class dbTest {	
	public static void main(String[] args) throws Exception {

		String diver = "oracle.jdbc.driver.OracleDriver";
		String dbUrl = "jdbc:oracle:thin:@localhost:1521:xe";
		String id = "myid";
		String pw = "xptmxm1234";
		PreparedStatement psm = null;
		Connection conn = null; 

		String sql = "create table emp_temp (emp_no varchar2(10), emp_name varchar2(20))";
		
		try { 
			Class.forName(diver); 
			conn = DriverManager.getConnection(dbUrl,id,pw);  
			psm = conn.prepareStatement(sql); 
			psm.executeQuery(); 
			
		}catch(Exception e){
			e.printStackTrace();
			
		} finally {
			
			if(psm != null) {
				psm.close();  
			}
			if(conn != null) {
			conn.close();
			}
		}
	}			
}

기본적으로 사용할 소스 구조 입니다.

create문이 정상적으로 작동된 모습입니다.

 

Insert

String sql = "insert into emp_temp (emp_no, emp_name) values('01', '테스트')";
		
		try { 
			Class.forName(diver); 
			conn = DriverManager.getConnection(dbUrl,id,pw);  
			psm = conn.prepareStatement(sql); 
			int result = psm.executeUpdate();
			System.out.println("결과값 : " + result);
			
			
		}catch(Exception e){
			e.printStackTrace();
			
		} finally {
			
			if(psm != null) {
				psm.close();  
			}
			if(conn != null) {
			conn.close();
			}
		}

Create문의 소스에

sql문과 try catch 부분만 수정한 소스입니다.

 

Create문과의 차이점은 

executeQuery -> executeUpdate으로 변경된 점입니다.

 

executeUpdate는 결과를 int 타입으로 반환받을 수 있습니다.

 

 

Update

String sql = "update emp_temp set emp_name = ? where emp_no = ?";
		
		try { 
			Class.forName(diver); 
			conn = DriverManager.getConnection(dbUrl,id,pw);  
			psm = conn.prepareStatement(sql); 
			psm.setString(1, "이름변경");
			psm.setString(2, "01");
			int result = psm.executeUpdate();
			System.out.println("결과값 : " + result);
			
			
		}catch(Exception e){
			e.printStackTrace();
			
		} finally {
			
			if(psm != null) {
			psm.close();  
			}
			if(conn != null) {
			conn.close();
			}
		}

 

기본적인 구조는 Insert 소스와 동일합니다.

다만 sql문에 물음표 표시가 있으실 텐데요.

이 부분은 가변적으로 처리할 수 있습니다.

 

preparedstatement의 setString을 이용하면

물음표의 순서에 따라 값을 할당하여 처리할 수 있습니다.

 

Delete

		String sql = "delete emp_temp where emp_no = ?";
		
		try { 
			Class.forName(diver); 
			conn = DriverManager.getConnection(dbUrl,id,pw);  
			psm = conn.prepareStatement(sql); 
			psm.setString(1, "01");
			int result = psm.executeUpdate();
			System.out.println("결과값 : " + result);
			
			
		}catch(Exception e){
			e.printStackTrace();
			
		} finally {
			
			if(psm != null) {
			psm.close();  
			}
			if(conn != null) {
			conn.close();
			}
		}

정상적인 처리로 인해 값이 삭제된 모습입니다.

반응형

+ Recent posts