본문 바로가기
개발/DB 커넥션

[jsp + mysql] 연결 테스트 예제 (PreparedStatement)

by 언제나초심. 2011. 5. 6.
반응형

<%@ page contentType="text/html;charset=utf-8" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<% request.setCharacterEncoding("utf-8"); %>
<% response.setContentType("text/html; charset=utf-8"); %>
<%
//디비연결 변수
Connection  conn  = null;
PreparedStatement   pstmt  = null;
ResultSet   rs    = null;

//쿼리 생성
String query      = " SELECT * FROM JSP_E2_TODO ";

try {
    // Oracle Connection Start
    Context initCtx = new InitialContext();
    Context envCtx = (Context)initCtx.lookup("java:/comp/env");
    DataSource ds = (DataSource)envCtx.lookup("jdbc/mysql");
    conn = ds.getConnection();

    //쿼리 적용
    pstmt = conn.prepareStatement(query);

    //파라미터 적용
    pstmt.setString(1, "파라미터 테스트");
    rs = pstmt.executeQuery();

    // 쿼리 결과 보여주기
    while(rs.next()) {
        out.println(rs.getString(2));
    }

}catch(SQLException se){
    out.println("[CONTENT]쿼리 에러 : SQLException ");
}catch(NullPointerException ne){
    out.println("[CONTENT]널 에러 : NullPointerException ");
}catch(Exception e){
    out.println("[CONTENT]에러 : Exception ");
} finally { 
    if (rs != null) try {rs.close(); }catch(SQLException ex) {}
    if (pstmt != null) try {pstmt.close(); } catch(SQLException ex) {}
    if (conn != null) try {conn.close(); }catch(SQLException ex) {}
}
%>


반응형