案例 查询account账户表数据,封装为Account 存储到ArrayList
package JDBC.DEMO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class JdbcTest {
public static void main(String[] args) throws Exception {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取链接
String url = "jdbc:mysql:///db1?useSSL=false";
String username = "root";
String password = "1234";
Connection connection = DriverManager.getConnection(url, username, password);
//3.定义sql
String sql = "select * from account";
//4.获取statement对象
Statement statement = connection.createStatement();
//5.执行sql
ResultSet resultSet = statement.executeQuery(sql);
List<Account> accounts = new ArrayList<>();
//6.处理结果 遍历res中所有数据
// 6.1 光标向下移动一行,并且判断当前行是否有数据
while (resultSet.next()){
// 获取数据
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
double money = resultSet.getDouble(3);
Account account = new Account(id ,name ,money);
accounts.add(account);
}
for (Account account : accounts) {
System.out.println(account);
}
}
}
package JDBC.DEMO;
public class Account {
private int id;
private String name;
private double money;
public Account() {
}
public Account(int id, String name, double money) {
this.id = id;
this.name = name;
this.money = money;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}