package JDBCtest;
import org.junit.jupiter.api.Test;
import pojo.Account;
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 {
@Test
public void select() throws Exception{
/*1注册驱动* 2获取链接* 3获取传输器* 4执行sql语句* 5处理结果集* 6关闭连接*/
//1注册驱动
Class .forName("com.mysql.jdbc.Driver");
//2获取链接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jt_db?characterEncoding=utf-8&serverTimezone=UTC","root","admin");
System.out.println("conn" + conn);
//3获取传输器
Statement statement = conn.createStatement();
// 4执行sql语句
String sql = "select * from account";
//5处理结果集
ResultSet rs = statement.executeQuery(sql);
List list = new ArrayList();
while(rs.next()){
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getDouble("money"));
list.add(account);
}
System.out.println(list);
//6关闭连接
rs.close();
statement.close();
conn.close();
}
}
package pojo;
public class Account {
private int id;
private String name;
private double 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 +
'}';
}
}