package com.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<Student> students = findAll();
if (students == null) {
System.out.println("Failed");
} else {
System.out.println("students: " + students.size());
for (Student student : students) {
System.out.println(student.toString());
System.out.println("==========================");
}
}
}
private static List<Student> findAll() {
List<Student> students = new ArrayList<Student>();
try {
PreparedStatement preparedStatement = ConnectDB.connection().prepareStatement("select * from student where age >= ? and age <= ? and status = ?");
preparedStatement.setInt(1, 18);
preparedStatement.setInt(2, 25);
preparedStatement.setBoolean(3, true);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Student student = new Student();
student.setDob(resultSet.getDate("dob"));
student.setAge(resultSet.getInt("age"));
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
student.setStatus(resultSet.getBoolean("status"));
students.add(student);
}
} catch (Exception e) {
students = null;
} finally {
ConnectDB.disconnect();
}
return students;
}
public static class Student {
private int id;
private String name;
private int age;
private boolean status;
private Date dob;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
@Override
public String toString() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", status=" + status + ", dob="
+ simpleDateFormat.format(dob) + "]";
}
}
public class ConnectDB {
private static Connection connection;
public static Connection connection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "username",
"password");
} catch (Exception e) {
e.printStackTrace();
connection = null;
}
return connection;
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}