JAVA学习笔记(五十二)- 开发DAO层的经典实现

StudentDAO接口,定义学生相关的操作


/*
 * StudentDAO接口,定义学生相关的操作
 */
public interface StudentDAO {

    //添加学生
    public void addStudent(Student stu);

    //删除学生
    public void deleteStudent(int id);

    //修改学生
    public void updateStudent(Student stu);

    //查询所有学生
    public List<Student> getAllStudents();

    //根据学号查询学生
    public Student getStudentById(int id);

    //根据条件模糊查询
    public List<Student> getStudentsByCondition(String name,String gender);
}

StudentDAOImpl实现类,实现相关的操作

/*
 * StudentDAOImpl实现类,实现相关的操作
 */
public class StudentDAOImpl implements StudentDAO {
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;

    @Override
    public void addStudent(Student stu) {
        String sql="insert into student values (null,?,?,?,?,?)";
        try {
            conn=DBUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, stu.getName());
            pstmt.setInt(2, stu.getAge());
            pstmt.setString(3, stu.getGender());
            pstmt.setString(4, stu.getPhone());
            pstmt.setString(5, stu.getEducation());
            pstmt.executeUpdate();
            System.out.println("添加學生成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, pstmt, conn);
        }
    }

    @Override
    public void deleteStudent(int id) {
        String sql="delete from student where id=?";
        try {
            conn=DBUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setObject(1, id);
            pstmt.executeUpdate();
            System.out.println("删除學生成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, pstmt, conn);
        }
    }

    @Override
    public void updateStudent(Student stu) {
        String sql="update student set name=?,age=?,gender=?,phone=?,education=? where id=?";
        try {
            conn=DBUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, stu.getName());
            pstmt.setInt(2, stu.getAge());
            pstmt.setString(3, stu.getGender());
            pstmt.setString(4, stu.getPhone());
            pstmt.setString(5, stu.getEducation());
            pstmt.setInt(6, stu.getId());
            pstmt.executeUpdate();
            System.out.println("修改學生成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, pstmt, conn);
        }
    }

    @Override
    public List<Student> getAllStudents() {
        List<Student> students=new ArrayList<Student>();
        String sql="select * from student";
        try {
            conn=DBUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            rs=pstmt.executeQuery();
            while(rs.next()){
                Student stu=new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4),rs.getString(5),rs.getString(6));
                students.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, pstmt, conn);
        }
        return students;
    }

    @Override
    public Student getStudentById(int id) {
        Student stu=null;
        String sql="select * from student where id=?";
        try {
            conn=DBUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs=pstmt.executeQuery();
            if(rs.next()){
                stu=new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4),rs.getString(5),rs.getString(6));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, pstmt, conn);
        }
        return stu;
    }

    @Override
    public List<Student> getStudentsByCondition(String name, String gender) {
        List<Student> students=new ArrayList<Student>();
        String sql="select * from student where name like ? and gender=?";
        try {
            conn=DBUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setObject(1, "%"+name+"%");//注意此写法
            pstmt.setObject(2, gender);
            rs=pstmt.executeQuery();
            while(rs.next()){
                Student stu=new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4),rs.getString(5),rs.getString(6));
                students.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, pstmt, conn);
        }
        return students;
    }
}

实体类Student,POJO

/*
 * 实体类Student,POJO
 */
public class Student {
    private int id;
    private String name;
    private int age;
    private String gender;
    private String phone;
    private String education;

    public Student() {
        super();
    }

    public Student(int id, String name, int age, String gender, String phone,
            String education) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.education = education;
    }

    public Student(String name, int age, String gender, String phone,
            String education) {
        super();
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.education = education;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEducation() {
        return education;
    }

    public void setEducation(String education) {
        this.education = education;
    }

}

测试类

import java.util.Iterator;
import java.util.List;
/*
 * 测试类
 */
public class Test {
    public static void main(String[] args) {
        //添加学生
        StudentDAO sd=new StudentDAOImpl();
        sd.addStudent(new Student("tom",20,"男","110","本科"));

        //删除学生
        sd.deleteStudent(2);

        //修改学生
        sd.updateStudent(new Student(5, "汤姆", 25, "男", "112", "研究生"));

        //查询所有学生
        List<Student> students=sd.getAllStudents();
        Iterator<Student> it=students.iterator();
        while(it.hasNext()){
            Student stu=it.next();
            System.out.println(stu.getId()+","+stu.getName()+","+stu.getEducation());
        }

        //根据编号查询学生
        Student stu=sd.getStudentById(5);
        System.out.println(stu.getId()+","+stu.getName()+","+stu.getEducation());

        //模糊查找
        List<Student> students=sd.getStudentsByCondition("姆", "男");
        Iterator<Student> it=students.iterator();
        while(it.hasNext()){
            Student stu=it.next();
            System.out.println(stu.getId()+","+stu.getName()+","+stu.getEducation());
        }
    }
}

数据库工具类

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

/*
 * 数据库工具类
 */
public class DBUtil {
    //获取数据库连接
    public static Connection getConnection(){
        Connection conn=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭所有资源
    public static void closeAll(ResultSet rs,Statement stmt,Connection conn){
        try {
            if(rs!=null)
                rs.close();
            if(stmt!=null)
                stmt.close();
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
时间: 2024-10-27 04:03:04

JAVA学习笔记(五十二)- 开发DAO层的经典实现的相关文章

Java学习笔记—第十二章 Java网络编程入门

第十二章  Java网络编程入门 Java提供的三大类网络功能: (1)URL和URLConnection:三大类中最高级的一种,通过URL网络资源表达方式,可以很容易确定网络上数据的位置.利用URL的表示和建立,Java程序可以直接读入网络上所放的数据,或把自己的数据传送到网络的另一端. (2)Socket:又称"套接字",用于描述IP地址和端口(在Internet中,网络中的每台主机都有一个唯一的IP地址,而每台主机又通过提供多个不同端口来提供多种服务).在客户/服务器网络中,当客

JAVA学习第五十二课 — IO流(六)File对象

File类 用来给文件或者文件夹封装成对象 方便对文件与文件夹的属性信息进行操作 File对象可以作为参数传递给流的构造函数 一.构造函数和分隔符 public static void FileDemo() {//构造函数演示 //可以将一个已存在或不存在的文件或目录封装成File对象 File file = new File("d:\\a.txt"); File file2 = new File("d:","a.txt"); File file

JAVA学习笔记(三十二)- 字符流 FileReader &amp; FileWriter

标题 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream;

JAVA学习笔记(五十)- JDBC Java数据库连接

JDBC操作步骤 /* * JDBC操作步骤 * */ public class Test01 { public static void main(String[] args) { try { //1.加载并注册驱动 Class.forName("com.mysql.jdbc.Driver"); //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); System.out.println("注册驱动成功!&qu

JAVA学习笔记(五十九)- Socket编程

客户端 import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; /* * 客户端 */ public class Client { public static void main(String[] args) throws IOExcep

JAVA学习笔记(五十六)- 泛型 Generic Types

泛型 Generic Types import java.util.ArrayList; import java.util.List; /* * 泛型 Generic Types * 集合泛型 * 类泛型 * 方法泛型 */ public class Test01 { public static void main(String[] args) { // 1.集合泛型,保证集合中元素的类型安全 List<Integer> nums = new ArrayList<Integer>(

JAVA学习笔记(五十八)- InetAddress类与URL

InetAddress类 /* * InetAddress类   */ public class Test07 {    public static void main(String[] args) throws UnknownHostException {        //获取本机的InetAddress实例          System.out.println("*******获取本机... www.songtaste.com/user/10258631/infowww.songtast

JAVA学习笔记(五十四)- 事务Transaction与批处理

事务Transaction /* * 事务Transaction * JDBC默认开启自动提交事务,需要关闭,才能手动控制事务 * * 默认MySQL存储引擎为My...,其不支持事务处理,修改为InnoDB引擎 * create table 表名( ) engine=InnoDB default charset=utf8; * * InnoDB引擎默认关闭自动事务提交,修改MySQL为自动提交事务 * set autocommit=1; //1表示自动提交,0表示关闭自动提交 * show v

JAVA学习笔记(五十五)- 元数据 MetaData和可滚动的结果集

元数据 Meta Data /* * 元数据 Meta Data */ public class Test03 { Connection conn = null; PreparedStatement pstmt=null; ResultSet rs = null; public void test(){ conn=DBUtil.getConnection(); try { DatabaseMetaData dbmd=conn.getMetaData(); //获取数据库元数据 System.ou