我正在尝试从数据库中获取结果并将它们放入java中的表中。 我的数据库如下所示:
users[idu, username, password, ul]
teachers[idt, firstname, secondname, idu]
discipline[idd, name, idt]
class[idc, name, grade]
student[ids, idu, idc, firstname,secondname]
grades[idg, idd, ids, grade]
classskips[idcs, ids, date]
我的表格代码如下:
public void tablepanel(){
ConnectDB(serverip, serverport, serverdbname, serverusername, serverpassword);
Object[] columnNames = {"ID", "Firstname", "Secondname"};
ArrayList dataouter = new ArrayList();
try{
stgs = conn.createStatement();
getstudent = ("SELECT ids, firstname, secondname FROM student");
rsgs = stgs.executeQuery(getstudent);
rsmd = rsgs.getMetaData();
columnsNumber = rsmd.getColumnCount();
System.out.println(columnsNumber);
while(rsgs.next()){
ArrayList datainner = new ArrayList();
datainner.add(rsgs.getInt("ids"));
datainner.add(rsgs.getString("firstname"));
datainner.add(rsgs.getString("secondname"));
dataouter.add(datainner);
System.out.println(datainner);
}
System.out.println(dataouter);
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Error: " +ex);
}
JTable table = new JTable(dataouter, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
}
现在我如何将数据库中的结果添加到表中?
答案 0 :(得分:0)
创建一个TableModal并将其设置为表。另外,创建一个Modal类可能Student
包含id
,firstname
和secondname
字段以及getter和setter。创建TableModal
public class StudentsTableModal extends AbstractTableModel {
String[] columnNames = {"ID", "Firstname", "Secondname"};
Class[] types = { Integer.class, String.class, String.class };
private ArrayList<Student> data = new ArrayList<Student>();
public ArrayList<Student> getData() {
return data;
}
public void setData(ArrayList<Student> data) {
this.data = data;
fireTableDataChanged();
}
public int getRowCount() {
return data.size();
}
public int getColumnCount() {
return colNames.length;
}
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public String getColumnName(int column) {
return colNames[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Student s = data.get(rowIndex);
switch (columnIndex) {
case 0:
return s.getId();
case 1:
return s.getFirstname();
case 2:
return s.getSecondname();
}
return null;
}
}
现在创建一个这样的实例并设置表模态
StudentsTableModal modal=new StudentsTableModal();
table.setTableModal(modal);
从表中检索数据时,将每行存储到新的Student
对象并将该对象存储到ArrayList
,完成后,在模态上调用setData
方法使用此数据列表。