본문 바로가기

프로그래밍

[JSP+MYSQL] JSP에서 Mysql DB 읽어오기

반응형

<%@page language="java" import="java.util.*, java.sql.*" session="true" contentType="text/html; charset=UTF-8" %>
<%

Connection conn=null;
ResultSet rs=null;
Statement stmt=null;


try {
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB명","계정ID","계정비번");

} catch (SQLException ex) {
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
} finally {
 out.println(conn);
}

try {
 stmt = conn.createStatement();
    if (stmt.execute("SELECT * FROM 테이블명")) {
         rs = stmt.getResultSet();
    }
 while(rs.next()) {
  out.println(rs.getString(2));
  out.write("<BR>");
 }
 rs.close();
 stmt.close();
 conn.close();
} catch(Exception e) {
 out.println("rs.next() Error ");
 out.println(e.toString());
}
%>


빨간 부분은 각자의 설정에 따름.

반응형