将数据库中的数据转化为实体类并且存为集合中
首先在SQLyog中创建一个表为t_homework
对于表中的id字段设置为主键、非空和自增。
在表中随便写入几个数据
在IDEA中创建实体类Acount并设置变量与表中的字段相对应
package com.test.bean;
/**
* @date 2020/08/28
**/
public class Account {
//这里的变量需要跟数据库表中的字段相对应
private Integer id;
private String username;
private String password;
private String balance;
//提供满参和无参构造方法
public Account(Integer id, String username, String password, String balance) {
this.id = id;
this.username = username;
this.password = password;
this.balance = balance;
}
public Account() {
}
//提供四个变量的get()和set()方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBalance() {
return balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
//在这里提供toString方法,一会需要输出进行测试
@Override
public String toString() {
return "Account{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", balance='" + balance + '\'' +
'}';
}
}
接下来采用jdbc对数据中的数据进行查询
代码如下
package com.test.bean;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @date 2020/08/28
**/
public class Test01 {
@Test
public void testSelect(){
Connection connection=null;
PreparedStatement ps=null;
ResultSet rs=null;
//创建一个空集合来存储实体类
List<Account> list=new ArrayList<>();
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接,此处用户名和密码需要根据自己的来写
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","xxx","xxx");
//预编译
ps=connection.prepareStatement("select * from t_homework ");
//执行sql语句并返回结果
rs=ps.executeQuery();
while (rs.next()){
//每次通过循环把结果转为实体机,通过有参构造
Account account=new Account(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4));
//添加进集合
list.add(account);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
try {
connection.close();
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println(list.size());
//遍历输出集合
for (Account account : list) {
System.out.println(list);
}
}
}
结果如下
说明成功