JDBC: Statement vs. PreparedStatement

0

JDBC

목록 보기
3/4
post-thumbnail

아래 포스팅을 보고 공부했습니다
flatsun님 포스팅: Statement PreparedStatement 차이 알아보기


차이점

createStatement

이를 사용한 쿼리 수행 코드는 아래와 같다

    public boolean createTable() throws SQLException {
		boolean flag = false;
		
		String sql = "create table toys (";
				sql+= "No int primary key not null, ";
				sql+= "name varchar(20) not null, ";
				sql+= "manufacturing varchar(20) not null, ";
				sql+= "price int not null ";
				sql+= ")";
				
		Connection con = ConnectionManager.getConnection();
		Statement stmt = con.createStatement();
		int affectedCount = stmt.executeUpdate(sql);
		
		System.out.println("쿼리의 반환값은 :"+affectedCount);
		
		if(affectedCount == 0) {
			flag = true;
		}
		
		return flag;
	}

Statement 객체인 stmt에 executeUpdate(sql) 메서드를 사용할 때, 쿼리를 파라미터로 입력한다.
따라서 실행 전까지는 어떤 쿼리를 수행할 것인지 명확하지 않다.
(지금 수준에서는 간단해서 명확해 보인다)


preparedStatement

이를 사용한 쿼리 수행 코드는 아래와 같다

public boolean insertToy(String name, String manufacturing, int price) throws SQLException {
		boolean flag = false;
		
		String sql = "insert into toys (name, manufacturing, price) ";
				sql+= "values(";
				sql+= "?, ";
				sql+= "?, ";
				sql+= "? ";
				sql+= ");";
				
		Connection con = ConnectionManager.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		
		pstmt.setString(1, name);			// 첫 번째 물음표에 매개 변수로 받은 name 넣기 
		pstmt.setString(2, manufacturing);	// 두 번째에는 매개 변수로 받은 manufacturing 넣기
		pstmt.setInt(3, price);				// 세 번째에는 매개 변수로 받은 price 넣기
		
		int affectedCount = pstmt.executeUpdate();
		
		if(affectedCount > 0) {
			flag = true;
		}
		
		pstmt.close();	// 통로 닫기
		con.close();	// 연결 닫기 
		
		return flag;
	}//insertToy()

preparedStatement(sql)를 생성하는 시점에서 이미 쿼리가 파라미터로 들어가있는 것을 볼 수 있다.
즉, 쿼리를 미리 생성해둔다.
그 후 쿼리에 들어갈 Bind 변수(?)를 설정해주고, 쿼리를 실행한다.(executeUpdate())
그렇기 때문에 재사용률이 높고, 반복되는 작업에서 처리 속도가 빠르다.
객체를 여러 개 생성할 필요가 없다.

SQL Injection?

createStatement는 SQL Injection에 취약하다.
반면 preparedStatement에서는 SQL Injection이 발생하지 않는다.

0개의 댓글