private Connection Econn;
private DefaultTableModel examTable = new DefaultTableModel();
public StudentInfoFrame(int eid) {
initComponents();
this.e_id = eid;
try
{
jTable2.getParent().setBackground(Color.black);
SimpleDataSource.init();
Econn = SimpleDataSource.getConnection();
jTable2.setModel(examTable);
retrieveExams();
}
catch(SQLException | ClassNotFoundException e)
{
System.out.println(e);
}
}
private void retrieveExams()
{
try
{
Statement stat = Econn.createStatement();
String query = "SELECT date, name,forename,surname,status,Exam "+
"FROM studentexam sx INNER JOIN Exam e ON sx.ex_id = e.ex_id " +
"INNER JOIN employee em ON e.head = em.e_id WHERE st_id = "+this.e_id;
ResultSet result = stat.executeQuery(query);
if(result.first())
{
while(result.next())
{
String headname = result.getString("forename")+" "+result.getString("surname");
String name = result.getString("name");
int status = result.getInt("status");
String pres;
if(status == 1)
{
pres = "Yes";
}
else
{
pres = "No";
}
String exam;
if(result.getInt("Exam") == 1)
{
exam = "Yes";
}
else
{
exam = "No";
}
Date date = result.getDate("date");
int day = date.getDay();
int year = date.getYear()+1900;
int month = date.getMonth()+1;
String datum = year+"-"+month+"-"+day;
int row = examTable.getRowCount()+1;
examTable.insertRow(row, new Object[] { name,headname,datum, exam,pres });
}
}
}
This gives me this error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 > 0.
Any idea?
DefaultTableModel#insertRow
inserts an entry at a given index. It is not possible to insert an entry beyond the model's current row count
Replace
examTable.insertRow(row, new Object[] { name,headname,datum, exam,pres });
with
examTable.addRow(new Object[] { name,headname,datum, exam,pres });
Look at these lines:
if (result.first()) {
while(result.next()) {
Your SQL
would suggest that you are expecting a single record to be returned from your query. However, by calling ResultSet#first
, the cursor is advanced past the first possible row so your while
loop is never entered. Instead you could replace these lines with:
if (result.next()) {
Aside from this, use a PreparedStatement
rather than a Statement
to protect against SQL Injection attacks.