数据库里表t_student:no,name,sex,class,birth
import java.util.Date;
//封装
public class Student {
private int no;
private String name;
private int sex;
private String classno;
private Date birth;
public Student(int no, String name, int sex, String classno, Date birth) {
this.no = no;
this.name = name;
this.sex = sex;
this.classno = classno;
this.birth = birth;
}
public Student() {
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getClassno() {
return classno;
}
public void setClassno(String classno) {
this.classno = classno;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Student{" +
"no=" + no +
", name='" + name + '\'' +
", sex=" + sex +
", classno='" + classno + '\'' +
", birth=" + birth +
'}';
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static Date testStringConvertToDate(String s){//将String字符串转换为util.date类型
/*yyyy-MM-dd格式一定要与stringDate的格式一致*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(s);
return date;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC","root","密码");
stmt = conn.createStatement();
String sql1 = "select * from t_student order by no";
ResultSet resultSet = stmt.executeQuery(sql1);
while (resultSet.next()){
Student st = new Student(resultSet.getInt(1),
resultSet.getString(2),
resultSet.getInt(3),
resultSet.getString(4),
testStringConvertToDate(resultSet.getString(5)));
System.out.println(st);
}
}catch(Exception e){
e.printStackTrace();
}finally{
//6 释放资源
if(stmt != null){
try{
stmt.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}