JSP|DB接続-JDBC

12244 ワード


<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%!Connection connection;
	Statement statement;
	ResultSet resultSet;

	/*
	1. 사용할 드라이버
	2. 드라이버 파일 위치
	3. SQL 접근 id
	4. 접근 비번
	5. 실행할 쿼리
	*/
	String driver = "oracle.jdbc.driver.OracleDriver";
	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	String uid = "scott";
	String upw = "tiger";
	String query = "select * from member";%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>

	<%
	try {

		Class.forName(driver); //oracle.jdbc.driver.OracleDriver
		connection = DriverManager.getConnection(url, uid, upw); //jdbc:oracle:thin:@localhost:1521:xe
		statement = connection.createStatement();
		resultSet = statement.executeQuery(query); //select * from member

		//  query 데이터가 있는 게 true일 경우 정보 출력
		while (resultSet.next()) {
			String id = resultSet.getString("id");
			String pw = resultSet.getString("pw");
			String name = resultSet.getString("name");
			String phone = resultSet.getString("phone");

			out.println("아이디 : " + id + ", 패스워드 : " + pw + ", 이름 : " + name + ", 전화번호 : " + phone + "<br />");
		}

		//Exception e: 에러
	} catch (Exception e) {
		//에러출력
		e.printStackTrace();
	} finally {
		try {
			if (resultSet != null)
		resultSet.close();
			if (statement != null)
		statement.close();
			if (connection != null)
		connection.close();
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}
	%>

</body>
</html>