Please Enable JavaScript!
Mohon Aktifkan Javascript![ Enable JavaScript ]

[JDBC]전화번호부 DB

2010. 5. 28. 11:47programming/JDBC

728x90

create table telbook(
tb_id int not null primary key auto_increment,
tb_name varchar(15) not null,
tb_tel varchar(15) not null
);

auto_increment 자동적으로 숫자 증가

===================================
>>>>>>>> 1. telbookDB_in.jsp
===================================
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>
<center>

<form name=form1 method=post action=telbookDB_put.jsp>
<table border=1 cellspacing="1" cellpadding="5">
  <tr><td colspan=2 align=center> 전화번호 입력 </td></tr>
  <tr>
    <td>이름</td>
    <td><input type=text name=name size=15></td> 
    </tr>
    <tr>
    <td>전화번호</td>
    <td><input type=text name=tel size=15></td>
 </tr>
 <tr>
  <td colspan=2 align=center>
    <input type=submit value="저장">
    <input type=reset value="취소"></td></tr>
</table>
</form>

<br><br>

<form name=form2 method=post action=telbookDB_get.jsp>
<table border=1 cellspacing="1" cellpadding="5">
  <tr><td colspan=2 align=center> 전화번호 검색 </td></tr>
  <tr>
    <td>이름</td>
    <td><input type=text name=name_f size=15></td> 
  <tr><td colspan=2 align=center>
    <input type=submit value="검색">
    <input type=reset value="취소"></td></tr>
</table>
</form>
</center>
</body>
</html>

===================================
>>>>>>>> 2. telbookDB_put.jsp
===================================
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<% request.setCharacterEncoding("euc-kr"); %>

<jsp:useBean id="tb" class="TelBook.TelbookDBBean" scope="application" />
<jsp:setProperty name="tb" property="*" />

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<center>
<HR>
<% 
tb.setTelbook();
%>
<script>
alert("추가 되었습니다!!");
history.go(-1);
</script>

</center>
</body>
</html>


===================================
>>>>>>>> 3. telbookDB_get.jsp
===================================
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<% request.setCharacterEncoding("euc-kr"); %>
<jsp:useBean id="tb" class="TelBook.TelbookDBBean" scope="application" />
<jsp:setProperty name="tb" property="name_f" />
<!-- getName_f() -->

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<center>
<%
tb.getTelbook();
%>
<table border=1 cellspacing="1" cellpadding="5">
  <tr>
    <td colspan=2 align=center> 검색 정보 </td></tr>
  <tr>
    <td>이름</td>
    <td><jsp:getProperty name="tb" property="name_f" /></td></tr>
  <tr>
    <td>전화번호</td>
    <td><jsp:getProperty name="tb" property="tel_f" /></td></tr>
</table>

</center>
</body>
</html>
===================================
>>>>>>>> 4. TelbookDBBean.java
===================================
package TelBook;
import java.sql.*;
public class TelbookDBBean {
private String name=""; //이름, 입력폼의 name 속성값과 반드시 일치 시킬 것
private String tel=""; //전화번호, 입력폼의 name 속성값과 반드시 일치 시킬 것
private String name_f=""; //검색된 이름 저장
private String tel_f=""; //검색된 이름에 해당하는 번호 저장
// 데이터베이스 연결관련 변수 선언
Connection conn = null;
PreparedStatement pstmt = null;
// 데이터베이스 연결관련정보를 문자열로 선언
String jdbc_driver = "com.mysql.jdbc.Driver";
String jdbc_url = "jdbc:mysql://localhost:3306/jspdb";
// 데이터베이스 연결 메서드
void connect() 
{
// JDBC 드라이버 로드
try {
Class.forName(jdbc_driver);
// 데이터베이스 연결정보를 이용해 Connection 인스턴스 확보
conn = DriverManager.getConnection(jdbc_url,"root","ce1116");
} catch (Exception e) {
e.printStackTrace();  // 어떤 예외가 발생했는지 출력
}
}
// 데이터베이스 연결 종료 메서드
void disconnect() 
{
if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 게시물 등록 메서드
public void setTelbook()
{
connect(); // 데이터 베이스 연결
String sql ="insert into telbook(tb_name,tb_tel) values(?,?)";
try {
pstmt = conn.prepareStatement(sql);
// 인자로 받은 GuestBook 객체를 통해 사용자 입력값을 받아 SQL 완성후 입력 처리
pstmt.setString(1,this.name); // values(?,?) 부분 파라미터
pstmt.setString(2,this.tel); // ? 가 String 형이기 때문에
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
finally { // 예외가 발생하든 안하든 실행
disconnect(); // 종료
}
}

// 게시물 하나의 모든 정보를 가지고 오는 메서드
public void getTelbook() 
{
connect(); 
String sql = "select * from telbook where tb_name=?";
// select 레코드 반환.
// tb_name의 값을 찾아줌.
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name_f);
ResultSet rs = pstmt.executeQuery();
// select 레코드 반환에 의해서 rs 객체에 담아둔다. ( ResultSet의 타입으로 )
if( rs.next() ){ // 여러 개의 레코드가 있다.(레코드 전체를 반환)
 next() -> 전체 레코드 집합에서 한 개씩 가져온다.
this.name_f = rs.getString("tb_name");  // rs.getString("검색할 필드명");
this.tel_f = rs.getString("tb_tel");
} else {

this.tel_f = "등록된 이름이 아닙니다";
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
disconnect();
}
}

public String getName() { return name;}
public void setName(String name) { this.name = name;}
public String getName_f() { return name_f;}
public void setName_f(String name_f) { this.name_f = name_f;}
public String getTel() { return tel;}
public void setTel(String tel) { this.tel = tel;}
public String getTel_f() { return tel_f;}
public void setTel_f(String tel_f) { this.tel = tel_f;}

}

728x90

'programming > JDBC' 카테고리의 다른 글

Database 연결 확인 + 이클립스 개발환경 만들기  (0) 2010.06.12
JDBC 드라이브 설치.  (0) 2010.06.12
[JDBC]방명록 만들기  (0) 2010.06.04
jdbctest.jsp 실습 12주  (0) 2010.05.26
JDBC 데이터 베이스 생성  (0) 2010.05.19