Java_jdbc 基础笔记之八 数据库连接(写一个查询Student对象的方法)

public Student getStudent(String sql, Object... args) {
        // 查询Student对象
        Student stu = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCTools.getConnection();
            ps = conn.prepareStatement(sql);
            // 填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                stu = new Student();
                stu.setFlowId(rs.getInt(1));
                stu.setType(rs.getInt(2));
                stu.setiDCard(rs.getString(3));
                stu.setExamCard(rs.getString(4));
                stu.setStudentName(rs.getString(5));
                stu.setLocation(rs.getString(6));
                stu.setGrade(rs.getInt(7));

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭
            JDBCTools.close(rs, ps, conn);
        }

        return stu;

    }

    @Test
    public void testGet(){
        String sql="SELECT flow_id flowId, type, id_card iDCard, "
                + "exam_card examCard, student_name studentName, "
                + "location, grade " + "FROM examstudent WHERE flow_id = ?";
        Student stu=getStudent(sql,4);
        System.out.println(stu);

    }

这是原始的数据表 

这是查询结果: 

转:  https://blog.csdn.net/YL1214012127/article/details/48296639

原文地址:https://www.cnblogs.com/fps2tao/p/12023825.html