Search code examples
javaswingsqlitejtabledatamodel

Best way for populating JTable with data from SQLite4java


I'm using sqlite4java and i want to display the query results in the Table component. I have made a DataModel and it works by getting each call value as my code shows below, but it is really slow when the query result has 10k or more rows and 10 columns.

public Object getValueAt(final int row,final int column) {
   return queue.execute(new SQLiteJob<Object>() {
        @Override
        protected Object job(SQLiteConnection connection) throws SQLiteException {
            Object Result = "";
            SQLiteStatement st = connection.prepare("SELECT * from test LIMIT ?,1 ;");
            st.bind(1, row);
            while (st.step()) {
                Result = st.columnString(column);
            }
            st.dispose();
            return Result;
        }
    }).complete();


}

What is the correct way to get this working as fast as possible?


Solution

  • Currently you will execute a query each time the getValueAt method is called (which is called a lot). Typically a database query is not fast enough for usage in this method (certainly not when using a remote database).

    A better approach is to query your database once (well, depends a bit on the size of the data you retrieve from your DB), put it in a TableModel and build your table using that TableModel.

    SO contains lots of questions and answers for this problem so a quick search would point you to a lot of sample code. I copied this link from one of those questions. All credits for the code on that page go of course to the author (who is also present here, but I forget his username on SO)