jdbc的封装练习


import mystring.demo4.Teacher;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


//从数据库中获取数据封装在某个类中,再存在集合中
public class JDBCdemo6 {
    public static void main(String[] args) {
        List<Teacher> list = findAll();
        for (Teacher teacher : list) {
            System.out.println(teacher);
        }
    }

    public static List<Teacher> findAll(){
        Connection connection = null;
        Statement statement = null;
        List<Teacher> teachers = null;
        ResultSet resultSet = null;
        try {
            teachers = new ArrayList<>();
            Teacher teacher = new Teacher();
            connection = JDBCUntils.getConnection();
            statement = connection.createStatement();
            String sql = "select * from student";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                teacher.setName(name);
                teacher.setAge(age);
                teachers.add(teacher);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUntils.close(connection,statement,resultSet);
        }
        return teachers;
    }
}


posted @ 2021-05-05 11:41  code-G  阅读(32)  评论(0编辑  收藏  举报