承接上文链接:
JavaWeb课程复习资料(二)——idea创建JDBC(FactoryDB)
本文会将【resultSet】形式的数据转为list<T>的形式
1、创建【com.item.pojo】包,并创建表对应的类【UserInfo】
需要私有化的属性,set、get、所有参数的构造方法、空构造方法。
package com.item.pojo; import java.util.Date; public class UserInfo { private int id; private Date createDate; private String userName; private String introduce; public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } public UserInfo(int id, Date createDate, String userName, String introduce) { this.id = id; this.createDate = createDate; this.userName = userName; this.introduce = introduce; } public UserInfo() { } }
2、在【com.item.demo/Action.java】中完成测试
由于实际操作中候纯粹的做【add】操作,故而使用LinkedList进行操作。
package com.item.demo; import com.item.jdbc.FactoryDB; import com.item.pojo.UserInfo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; public class Action { public static void main(String[] args) { Connection conn = FactoryDB.GetConnection(); try { PreparedStatement pre = conn.prepareStatement("select * from userinfo"); ResultSet res = pre.executeQuery(); //由于只做添加操作,故而使用LinkedList LinkedList<UserInfo> list=new LinkedList<UserInfo>(); while (res.next()){ list.add(new UserInfo(res.getInt(1),res.getDate(2), res.getString(3),res.getString(4))); } for(UserInfo info:list){ System.out.print("id:"+info.getId()+"\t"); System.out.print("createDate:"+info.getCreateDate()+"\t"); System.out.print("userName:"+info.getUserName()+"\t"); System.out.println("introduce:"+info.getIntroduce()+"\t"); } FactoryDB.Close(conn,pre,res); } catch (SQLException e) { e.printStackTrace(); } } }
完成所有操作。