Java_jdbc 基础笔记之九 数据库连接 (查询Customer对象的方法)

/**
     * 
     * 写一个查询Customer对象的方法
     * 
     */
    public Customer getCustomer(String sql, Object... args) {
        Customer customer = 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()) {
                customer = new Customer();
                customer.setId(rs.getInt(1));
                customer.setName(rs.getString(2));
                customer.setEmail(rs.getString(3));
                customer.setBirth(rs.getDate(4));

            }

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

        return customer;

    }
    @Test
    public void testGet1(){
        String sql="SELECT id,name,email,birth FROM customers where id=?";
        Customer cust=getCustomer(sql,3);
        System.out.println(cust);

    }

原始的数据表 

查询的结果 

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

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