개발관련이야기들/JSP & Servlet

데이터베이스 예제(DAO)

안돌이 2006. 7. 24. 22:15

-- NumberDAO.java -- (DAO)


package com.wspark.web.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class NumberDAO {
public int get(int no) throws SQLException {
 int result = -1;
 Connection c = null;
 Statement stmt = null;
 try {
  //Connection의 생성(jdbc:데이터베이스종류:DB, user, password)
  c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "1234"); 
  stmt = c.createStatement();
  ResultSet rs = stmt.executeQuery("select " + no);
  while (rs.next()) {
   //no의 값에 상관없이 하나의 Columm만을 가져온다.
   result = rs.getInt(1);
  }   
  rs.close();
  c.close();
 } catch (SQLException e) {
  throw e;
 } finally {
  try {
   if (stmt != null) {
    stmt.close();
   }
  } catch (SQLException e) {}
 
  try {
   if (c != null) {
    c.close();
   }
  } catch (SQLException e) {
  }
 }
 return result;
}
}