Java 자습 - JDBC DAO

5255 단어
JDBC 기반 DAO 설계 인스턴스
DAO=DataAccess Object
데이터 액세스 객체
실제로는 ORM의 사고방식을 활용하여 데이터베이스와 관련된 조작을 모두 이 클래스에 봉하여 다른 곳에서는 JDBC의 코드를 볼 수 없다
1단계: DAO 인터페이스
package jdbc;
  
import java.util.List;
 
import charactor.Hero;
  
public interface DAO{
    //  
    public void add(Hero hero);
    //  
    public void update(Hero hero);
    //  
    public void delete(int id);
    //  
    public Hero get(int id);
    //  
    public List list();
    //    
    public List list(int start, int count);
}

2단계: Herodao
인터페이스 DAO를 위한 설계 클래스 HeroDAO
4
  • 드라이버의 초기화를 구조 방법인 Herodao에 두었습니다:public Herodao () {try {Class. forName ("com.mysql.jdbc.Driver");catch (ClassNotFoundException e) { e.printStackTrace(); } }

  • 드라이버 초기화는 한 번만 실행하기 때문에 여기에 두는 것이 더 적합하고 다른 방법에도 쓸 필요가 없고 코드가 더욱 간결하다
    4
  • get Connection 방법을 제공하여 모든 데이터베이스에 연결하는 작업을 되돌려주려면 데이터베이스 연결 Connection을 미리 가져와야 한다. 예전에는 방법마다 하나씩 썼는데 비밀번호를 바꾸려면 곳곳이 수정되어야 한다.이런 방식을 통해 이 한 곳만 고치면 된다.코드는 유지보수도 쉬워지고 간결해졌어요.
     package jdbc;
     import java.sql.Connection;
      
     import java.sql.DriverManager;
     import java.sql.PreparedStatement;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;
     import java.util.ArrayList;
     import java.util.List;
       
     import charactor.Hero;
       
     public class HeroDAO implements DAO{
       
         public HeroDAO() {
             try {
                 Class.forName("com.mysql.jdbc.Driver");
             } catch (ClassNotFoundException e) {
                 e.printStackTrace();
             }
         }
       
         public Connection getConnection() throws SQLException {
             return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root",
                     "admin");
         }
       
     public int getTotal() {
         int total = 0;
         try (Connection c = getConnection(); Statement s = c.createStatement();) {
    
             String sql = "select count(*) from hero";
    
             ResultSet rs = s.executeQuery(sql);
             while (rs.next()) {
                 total = rs.getInt(1);
             }
    
             System.out.println("total:" + total);
    
         } catch (SQLException e) {
    
             e.printStackTrace();
         }
         return total;
     }
    
     public void add(Hero hero) {
    
         String sql = "insert into hero values(null,?,?,?)";
         try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
    
             ps.setString(1, hero.name);
             ps.setFloat(2, hero.hp);
             ps.setInt(3, hero.damage);
    
             ps.execute();
    
             ResultSet rs = ps.getGeneratedKeys();
             if (rs.next()) {
                 int id = rs.getInt(1);
                 hero.id = id;
             }
         } catch (SQLException e) {
    
             e.printStackTrace();
         }
     }
    
     public void update(Hero hero) {
    
         String sql = "update hero set name= ?, hp = ? , damage = ? where id = ?";
         try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
    
             ps.setString(1, hero.name);
             ps.setFloat(2, hero.hp);
             ps.setInt(3, hero.damage);
             ps.setInt(4, hero.id);
    
             ps.execute();
    
         } catch (SQLException e) {
    
             e.printStackTrace();
         }
    
     }
    
     public void delete(int id) {
    
         try (Connection c = getConnection(); Statement s = c.createStatement();) {
    
             String sql = "delete from hero where id = " + id;
    
             s.execute(sql);
    
         } catch (SQLException e) {
    
             e.printStackTrace();
         }
     }
    
     public Hero get(int id) {
         Hero hero = null;
    
         try (Connection c = getConnection(); Statement s = c.createStatement();) {
    
             String sql = "select * from hero where id = " + id;
    
             ResultSet rs = s.executeQuery(sql);
    
             if (rs.next()) {
                 hero = new Hero();
                 String name = rs.getString(2);
                 float hp = rs.getFloat("hp");
                 int damage = rs.getInt(4);
                 hero.name = name;
                 hero.hp = hp;
                 hero.damage = damage;
                 hero.id = id;
             }
    
         } catch (SQLException e) {
    
             e.printStackTrace();
         }
         return hero;
     }
    
     public List list() {
         return list(0, Short.MAX_VALUE);
     }
    
     public List list(int start, int count) {
         List heros = new ArrayList();
    
         String sql = "select * from hero order by id desc limit ?,? ";
    
         try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
    
             ps.setInt(1, start);
             ps.setInt(2, count);
    
             ResultSet rs = ps.executeQuery();
    
             while (rs.next()) {
                 Hero hero = new Hero();
                 int id = rs.getInt(1);
                 String name = rs.getString(2);
                 float hp = rs.getFloat("hp");
                 int damage = rs.getInt(4);
                 hero.id = id;
                 hero.name = name;
                 hero.hp = hp;
                 hero.damage = damage;
                 heros.add(hero);
             }
         } catch (SQLException e) {
    
             e.printStackTrace();
         }
         return heros;
     }
    }
    

  • 자세한 내용, 클릭하여 알아보기: JDBC 기반 설계 DAO의 실례

    좋은 웹페이지 즐겨찾기