기본 콘텐츠로 건너뛰기

181129 Statement, PreparedStatement

Statement, PreparedStatement


0. 개요
 - SQL 질의문을 전달하는 인터페이스
 - 예외처리(try ~ catch문) 필수

1. connection
connection API - statement

1) Statement 객체는 Statement 인터페이스를 구현한 객체를
   Connection 클래스의 createStatement( ) 메서드로 호출하여 얻을 수 있음
2) Statement 객체가 생성되면 executeQuery( ) 메서드로 SQL문을 실행
3) 메서드의 인수로 SQL문을 담은 String객체를 DB에 전달
4) Statement는 값이 미리 입력되어 있는 정적인 쿼리문을 처리할 수 있음


connection API - preparedStatement

1) PreparedStatement 객체는 Connection 객체의
    preparedStatement( ) 메서드를 사용해서 생성
2) preparedStatement( )  메서드는 인수로 SQL문을 담은 String객체가 필요함
3) SQL문장이 미리 컴파일되고 실행하는 동안 인수값을 위한 공간을 확보할 수 있음
4) 실행될 때 매번 서버에서 분석해야 하는Statement와 달리
    PreparedStatement 객체는 한 번 분석되면 재사용이 용이
5) 각각의 인수는 위치홀더(placeholder)인 ?를 이용하여 SQL문장을 정의할 수 있음
6) 동일한 SQL문을 특정 값만 바꾸어서 여러 번 실행해야 할 때
6-1) 인수가 많아서 SQL문을 정리해야 될 필요가 있을 때 사용하면 유용

예)
public class DBConnection 
{
    public static Connection dbConn;
    
        public static Connection getConnection()
        {
            Connection conn = null;
            try {
                String user = "scott"
                String pw     = "tiger";
                String url     = "jdbc:oracle:thin:@localhost:1521:orcl";
                
                Class.forName("oracle.jdbc.driver.OracleDriver");        
                conn = DriverManager.getConnection(url, user, pw);
                
                System.out.println("Database connection complete\n");
                
            } catch (ClassNotFoundException e1) {
                System.out.println("DB loading failed:: "+cnfe.toString());
            } catch (SQLException e2) {
                System.out.println("DB connect failed:: "+sqle.toString());
            } catch (Exception e3) {
                System.out.println("unkonwn exception");
                e3.printStackTrace();
            }
            return conn;     
        }
}
cs


2. Statement

예)
import java.sql.Statement;
import java.sql.Connection;
import java.sql.SQLException;
public class StatementTest 
{
    public static void main(String args[])
    {
        Connection conn = null
        Statement stmt  = null
        
        try {
            conn = DBConnection.getConnection();    
            stmt = conn.createStatement();            
            
            String quary = "INSERT INTO TEST VALUES('tempId', 'tempPw', 'tempName')";
            int success = stm.executeUpdate(quary);
            
            if(success > 0)
                System.out.println("data insert complete");
            else
                System.out.println("data insert failed");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
cs



3. PreparedStatement

예)
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
public class PreparedStatementTest 
{
    public static void main(String args[])
    {
        Connection conn         = null
        PreparedStatement pstmt = null;
        
        try {
            String str = "INSERT INTO TEMP01 VALUES(?, ?, ?)";
            
            conn  = DBConnection.getConnection();
            pstmt = conn.prepareStatement(str);
            
            // 쿼리에 값을 세팅한다.
            // 여기서 1, 2, 3은 첫번째, 두번째, 세번째 위치홀더 라는 뜻
            pstm.setString(1"tempId1");
            pstm.setString(2"tempPw1");
            pstm.setString(3"tempName1");
            
            int success = pstmt.executeUpdate();
            
            if(success > 0)
                System.out.println("data insert complete");
            else
                System.out.println("data insert failed");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
cs