There is such table SQLite

col1 col2 col3 col4 row1 row1 row1 row1 row2 row2 row2 row2 row3 row3 row3 row3 row4 row4 row4 row4 row5 row5 row5 row5 

And there is a small Java program on NetBeans that should read the entire database and write it to the jTable. But it does this very crookedly when you delete all rows from the database, and it produces the following error when rows are added to the table:

 java.sql.SQLException: column 2 out of bounds [1,1] at org.sqlite.core.CoreResultSet.checkCol(CoreResultSet.java:84) at org.sqlite.core.CoreResultSet.markCol(CoreResultSet.java:97) at org.sqlite.jdbc3.JDBC3ResultSet.getString(JDBC3ResultSet.java:436) 

The code for getting data from the database:

 public static String[] [] getAllData(Connection con) { String[] [] res; int i = 1; int j = 1; res = new String[countRows(con)] [columnNames(con).size()]; stmt = con.createStatement(); query = "SELECT * FROM class;"; rs = stmt.executeQuery(query); rs.next(); while(i<columnNames(con).size()) { while(j<countRows(con)) { res [j] [i] = rs.getString(j); j++; } i++; } return res; } 

Code to write to the table:

 int i = 1; int j = 1; String[] [] res = DBController.getAllData(con); while(i<rows) { while(j<cols) { dtm.setValueAt(res [j] [i], j, i); j++; } i++; } 

Please help at least understand what caused this error.

  • indices and arrays in java and tables in sqlite start from 0, not from 1 - pavlofff

1 answer 1

You have incorrect data processing in the ResultSet.
The accepted processing pattern looks like this:

  public static String[][] getAllData(Connection con) { int i = 0; int j = 0; String[][] res = new String[countRows(con)][columnNames(con).size()]; try (Statement stmt = con.createStatement();) { String query = "SELECT * FROM class;"; try (ResultSet rs = stmt.executeQuery(query);) { while(rs.next()) { while (i < columnNames(con).size()) { while (j < countRows(con)) { res[j][i] = rs.getString(j + 1); j++; } i++; } } return res; } } } 

You only need to process when there are rows.
Very useful original material.
Also information about the columns can be obtained by

  rs.getMetaData() 
  • Thank you, your answer has helped to understand what the problem is! - Cropinghigh
  • If you are satisfied with the answer, mark it as true, thank you) - ezhov_da