Language/JSP

jsp db 연결 및 실행

적외선 2013. 11. 11. 15:15

<%@ page language="java" 
    contentType="text/html;charset=euc-kr" 
    import="java.util.*,java.io.*,java.sql.*"
%>

<%
    // 드라이버를 위해 웹서버 lib에 sqljdbc4.jar 저장 필요

    String strDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String strDBConn = "jdbc:sqlserver://IP ADDRESS:1433;DatabaseName=DBNAME";
    String strUserID = "USERID";
    String strUserPW = "USERPASSWORD";


    Class.forName(strDriver);
    Connection objConn = DriverManager.getConnection(strDBConn, strUserID, strUserPW);

    // Statement

     Statement objStmt = objConn.createStatement();
     ResultSet objRS = objStmt.executeQuery("SELECT TOP 5 * FROM TADMIN WITH (NOLOCK)");
 
     while(objRS.next()) {

          out.println(objRS.getString("AdminName") + "<BR>");
     }

    objRS.close();
    objStmt.close();

    // PreparedStatement
    // 쿼리 시 PreparedStatement를 쓰는 것이 좋은데, 이유는 쿼리가 캐시되므로 반복적인 작업에 속도가 유리.

    String strSQL = "SELECT TOP 5 * FROM TADMIN WITH (NOLOCK) WHERE ADMINID = ? ";

    PreparedStatement objPStmt = objConn.prepareStatement(strSQL);
    objPStmt.setString(1, "tiger");

    
    ResultSet objRS2 = objPStmt.executeQuery();
 
    while(objRS2.next()) {

    
        out.println(objRS2.getString("AdminName") + "<BR>");
    }
 
    objRS2.close();
    objPStmt.close();
    objConn.close();
%>