JBDC 데이터베이스 쿼리 실행
Connection 객체를 생성한 후에는 Connection으로 부터 쿼리 실행이 가능한 객체를 생성후 데이터베이스에 쿼리를 실행할 수 있다. 쿼리 실행 클래스에는 Statement, PreparedStatement, CallableStatement 3가지가 있다. 이번장에서는 3가지 클래스의 차이점만 설명하고 각 클래스의 사용방법과 자세한 설명은 뒷단원에서 예제와 함께 설명하겠다.
1. Statement
정적인 쿼리에 사용되며 하나의 쿼리를 사용하고 나면 더 이상 사용할 수 없다.
...
Connection conn = DriverManager.getConnection(url,id,pass);
Stirng name = "ace";
int age = 20;
Statement stmt = conn.createStatement();
String sql = "insert into member values('" +name+ "'," +age+ ")";
int r = stmt.executeUpdate(sql); // 쿼리를 실행할때 입력한다
stmt.close();
2. PreparedStatement
동적인 쿼리에 사용되며 하나의 객체로 여러번의 쿼리를 실행할 수 있다.
sql문장에 정해지지 않은 값을 물음표(?)로 표시하는 바인딩 변수를 사용할 수 있다. 바인딩 변수에 값을 할당하기 위하여 setXxx()메스드를 사용하며, 이 메서드는 물음표의 위치(첫번째 물음표면 1) 값과 실제 할당될 값을 매개변수로 갖는다.
...
Connection conn = DriverManager.getConnection(url,id,pass);
String sql = "insert into member(name, age) values (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql); //쿼리가 실행전에 미리 만들어져야 한다
pstmt.setString(1, "ace");
pstmt.setInt(2, 20);
pstmt.executeUpdate();
// pstmt객체를 재활용도 가능하다
pstmt.setString(1, "ruppy");
pstmt.setInt(2, 18);
pstmt.executeUpdate();
pstmt.close();
3. CallableStatement
데이터베이스 내의 스토어드 프로시저(Stored Procedure)를 호출할 때 사용한다.
Connection conn = DriverManager.getConnection(url,id,pass);
CallableStatement cs = conn.prepareCall("{call 프로시저이름(?,?,?)}");
//입력용
cs.setString(1,"ace");
cs.setInt(2, 20);
//출력용
cs.registerOutParameter(3, java.sql.Types.VARCHAR);
cs.execute();
cs.close();













