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;
    }
}


上一篇:JDBC ResultSet 通过反射获取实体对象或者对象的集合


下一篇:Entity FrameWork 中使用Lambda访问数据库性能优化