I am trying to populate my JTable from my embedded database that I have set up in Netbeans.
My database contains 3 rows and 3 columns that I'd like to insert into a JTable, and make the table visible in my GUI application.
However, I am getting a java.sql.SQLException error as the title says above and my table will not turn visible in my GUI application.
Here's is my code:
public void FillTable(JTable table, String Query)
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:derby:STOCK_CONTROL");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(Query);
//Remove previously added rows
while (table.getRowCount() > 0)
{
((DefaultTableModel) table.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = rs.getObject(i);
}
//The error is being generated here at 'rs.getRow()'
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
conn.close();
}
catch (InstantiationException |
IllegalAccessException |
ClassNotFoundException |
SQLException e)
{
System.out.println(e);
e.printStackTrace();
}
}
I then create my table and call the method as above:
JTable tigerTable = new JTable();
FillTable(tigerTable, "SELECT * FROM TIGER_INFO");
I've tried to find information as to why this error is being caused, but to no avail.
My question is, how do I correctly populate my JTable from my embedded database, whilst also straying away from this unknown error I have come about?
What does this error exactly mean? I'm unsure what a 'scroll cursor' is.
As documented in ResultSet.getRow()
:
Note: Support for the
getRow
method is optional forResultSet
s with a result set type ofTYPE_FORWARD_ONLY
[..]Throws:
[..]
SQLFeatureNotSupportedException
- if the JDBC driver does not support this method
You either need to ask for a scrollable cursor using
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Or - probably better - keep track of the row number yourself instead of using ResultSet.getRow()
. For example:
int rowIdx = 0;
while (rs.next()) {
Object[] row = new Object[columns];
// ...
((DefaultTableModel) table.getModel()).insertRow(rowIdx++, row);
}
It is been a while since I have done anything with swing, but it might even be simpler to just remove existing rows from the table model and call addRow
.