16.封装查询结果对象
封装简单粗暴的理解就是:假设你在超市买苹果,买一个你可以一个手拿走,买两个你可以用两只手拿走,但是如果买了20个勒,咋办勒,那就用一个袋子装起来!这就 封装思想。
1.封装一个产品对象 Product.java
1 package com.day01.station.model; 2 3 /** 4 * Created by Administrator on 2018/2/9. 5 */ 6 public class Product { 7 /** 8 * 类里面有三样 9 * 1.字段 10 * 2.构造方法 11 * 3.普通方法 12 13 */ 14 15 /** 16 * java里面取名称 规则 见名知意,驼峰命名 (当前来说除了类使用首字母大写的驼峰命名,其他都是首字母小写的驼峰命名) 17 * 18 * 封装一个字段 19 * private(权限) Integer(类型 int) id(名称) 20 */ 21 private Integer id; //id 22 private String productName; //产品名称 23 private Integer salePrice; 24 //提供get set 方法 25 26 27 public Integer getId() { 28 return id; 29 } 30 31 32 public void setId(Integer id) { 33 this.id = id; 34 } 35 36 public String getProductName() { 37 return productName; 38 } 39 40 public void setProductName(String productName) { 41 this.productName = productName; 42 } 43 44 public Integer getSalePrice() { 45 return salePrice; 46 } 47 48 public void setSalePrice(Integer salePrice) { 49 this.salePrice = salePrice; 50 } 51 52 // alt + insert 53 54 @Override 55 public String toString() { 56 return "Product{" + 57 "id=" + id + 58 ", productName='" + productName + '\'' + 59 ", salePrice=" + salePrice + 60 '}'; 61 } 62 }
2.查询结果使用对象接收
1 //查询 2 public Product query(int id) { 3 System.out.println("------我是查询方法----------"); 4 Product product = new Product();//袋子 5 try { 6 //1.加载 7 Class.forName("com.mysql.jdbc.Driver"); 8 //2.连接 9 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/station_demo", "root", "admin"); 10 //3.创建编译语句 11 String sql = "SELECT id,product_name,sale_price FROM product WHERE id=?"; 12 PreparedStatement preparedStatement = connection.prepareStatement(sql); 13 preparedStatement.setInt(1,id); 14 //4.执行语句 15 ResultSet resultSet = preparedStatement.executeQuery(); 16 //解析结果 17 while (resultSet.next()){//如果有在执行里面 18 int id1 = resultSet.getInt("id"); 19 String productName = resultSet.getString("product_name"); 20 int salePrice = resultSet.getInt("sale_price"); 21 //封装 袋子 22 //装 23 product.setId(id1); 24 product.setProductName(productName); 25 product.setSalePrice(salePrice); 26 } 27 //5.释放资源 28 resultSet.close(); 29 preparedStatement.close(); 30 connection.close(); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 return product; 35 }
17.面向对象之封装
1.对用户进行封装
1 package com.day01.station.model; 2 3 /** 4 * Created by Administrator on 2018/2/9. 5 * 6 * 用户的行为: 说 ==>方法表示 say() 7 * 8 * 用户的属性(字段): 年龄 性别 地址 姓名 9 * 10 */ 11 public class LoginUser { 12 // 用户的属性(字段): 年龄 性别 地址 姓名 13 14 private Integer age; 15 private String gender; // 男,女 ,妖 16 17 //私有化为 不能直接访问 ,那么间接访问 ==>提供一个方法 18 //提供一个设定值的方法 19 public void setGender(String gender){ 20 this.gender=gender; 21 } 22 23 public String getGender(){ 24 return gender; 25 } 26 27 public Integer getAge() { 28 return age; 29 } 30 31 public void setAge(Integer age) { 32 this.age = age; 33 } 34 35 //方法 36 public void say(){ 37 System.out.println("--------我是一个用户------"); 38 } 39 }