土办法完成set结果集封装
首先看根据数据库表的结构完成JavaBean(Dao)的编写
数据库表结构:
Mysql数据库 | JavaBean(Dao) |
---|---|
int id | private Integer id |
varchar(32) name | private String name |
char(4) sex | private String sex |
Datetime borndate | private Date borndate |
varchar(32) phone | private String phone |
对应dao层代码:
package com.ccl.dao;
import java.util.Date;
/**
* @author: 13749
* @date: 2021/9/23 17:18
* @description:
*/
public class Actor {
private Integer id ;
private String name;
private String sex;
private Date borndate;
private String phone;
public Actor() { //底层可能用到反射,反射需要无参构造器
}
public Actor(Integer id, String name, String sex, Date borndate, String phone) {
this.id = id;
this.name = name;
this.sex = sex;
this.borndate = borndate;
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBorndate() {
return borndate;
}
public void setBorndate(Date borndate) {
this.borndate = borndate;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Actor{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", borndate=" + borndate +
", phone='" + phone + '\'' +
'}';
}
}
在@Test模块中根据昨天的DruidUtil工具进行连接、获取相应表中数据,最后进行对ArrayList 的封装
@Test
public void testSelect02(){
Connection connection = null;
String sql = "select * from actor where id = ?";
PreparedStatement preparedStatement = null;
ResultSet set = null;
ArrayList<Actor > list = new ArrayList<Actor>();
try {
connection = JdbcUtilsByDruid.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
//执行sql
set = preparedStatement.executeQuery();
while(set.next()) {
int id = set.getInt("id");
String name = set.getString("name");
String sex = set.getString("sex");
Date borndate = set.getDate("borndate");
String phone = set.getString("phone");
//把得到的记录封装到Actor对象,放入到list集合
//相当于把查询到的记录结果封装到Actor对象
list.add(new Actor(id, name, sex, borndate, phone));
}
//输出list集合中的数据用foreach遍历结果集也可
System.out.println("list" + list);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtilsByDruid.close(set,preparedStatement,connection);
}
}
}
总结:封装成结果集之后即使连接关闭也不影响数据的使用
下一期:ApDBUtils工具的使用