我正在从数据库中检索数据,并希望将这些数据以对象的形式存储在我的arraylist中,并且可以在显示自定义表中使用。
我已经尝试过上一个相关查询的解决方案,但无法解决我的问题。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
public class Appointment {
public int no;
public String patient;
public String doctor;
public String disease;
public String scheduleDay;
public void setNo(int no){
this.no = no;}
public void setPatient(String patient){
this.patient = patient;}
public void setDoctor(String doctor){
this.doctor = doctor;}
public void setDisease(String disease){
this.disease = disease;}
public void setScheduleDay(String scheduleDay){
this.scheduleDay = scheduleDay;}
public int getNo(){
return no;}
public String getPatient(){
return patient;}
public String getDoctor(){
return doctor;}
public String getDisease(){
return disease;}
public String getScheduleDay(){
return scheduleDay;}
public Appointment(){
no = 0;
patient = "not set";
doctor = "not set";
disease = "not set";
scheduleDay = "not set";
}
public Appointment(int no, String patient, String doctor, String
disease, String scheduleDay){
setNo(no);
setPatient(patient);
setDoctor(doctor);
setDisease(disease);
setScheduleDay(scheduleDay);
}
public Appointment (Appointment ap){
no = ap.no;
patient = ap.patient;
doctor = ap.doctor;
disease = ap.disease;
scheduleDay = ap.scheduleDay;
}
public ArrayList<Appointment> appointmentArr() throws
ClassNotFoundException, SQLException {
String url = "jdbc:ucanaccess://D:/MC140202550/MC140202550.accdb";
Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "select * from Patient, Doctor where Patient.Disease =
Doctor.Specialization";
ResultSet rs = st.executeQuery(sql);
ArrayList<Appointment> appointments = new ArrayList<>();
while(rs.next()==true){
Appointment ap = new Appointment();
ap.setPatient(rs.getString(1));
ap.setDoctor(rs.getString(6));
ap.setDisease(rs.getString(4));
ap.setScheduleDay(rs.getString(8));
int i = 1;
ap.setNo(i);
i++;
appointments.add(ap);
System.out.println(ap.getNo() + " " + ap.getPatient() + " " +
ap.getDoctor() + " " + ap.getDisease() + " " + ap.getScheduleDay());
}
st.executeQuery(sql);
con.close();
st.close();
st.close();
return appointments;
}
}
我想在另一个主类中调用此约会类并打印存储在数组中的对象。
public class Main{
public static void main(String args[]){
Main main=new Main();
Appointment ap = new Appointment();
}
}
答案 0 :(得分:3)
您需要从main方法调用appointmentArr()
并将其分配给变量,然后打印。例如:
public class Main{
public static void main(String args[]){
Appointment ap = new Appointment();
List<Appointment> list = ap.appointmentArr();
// now you can iterate over list and print it.
for(Appointment ap: list){
System.out.println(ap.getNo() + " " + ap.getPatient() + " " +
ap.getDoctor() + " " + ap.getDisease() + " " + ap.getScheduleDay());
}
}
}