Springboot获取数据库内容
@Controller
public class Con {
@GetMapping("/sumView")
public String sumView(Model model ,String data) {
List students=new ArrayList<>();
String sql = "SELECT * FROM stu where 学号=?;"; // 请替换为实际的SQL语句
try {Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
int num=Integer.parseInt(data);
pstmt.setInt(1,num);
ResultSet rs = pstmt.executeQuery();
// List<Student> list=rs;
while (rs.next()) {
long id = rs.getLong("学号");
String name = rs.getString("姓名");
int age = 10;
String gender = rs.getString("性别");
String str = rs.getString("班级");
System.out.println("ID: " + id +
", Name: " + name +
", Age: " + age +
", Gender: " + gender +
", Class: " + str);
// 如果需要将数据传递给视图
Student student=new Student(id, name, age, gender, str);
students.add(student);
model.addAttribute("student", students);
model.addAttribute("num",data);
}
} catch (SQLException e) {
e.printStackTrace();
// 可以在这里添加错误处理逻辑
}
return "sumView";
}