Instead of going through the trouble of setting up variable columns, create a simple database table A:
row integer
col integer
content varchar
This gives you the flexibility to easily avoid empty entries and you have one database table row for every array item.
You have two options:
- Generate one database row for every element of your array including nulls, or
- Generate one database row for every element that is not null.
For option 1, this code will provide any element:
private String getElement(int row, int col) {
String result = null;
try {
if(rs.absolute(row*colNumber+col+1))
result=rs.getString("content");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return result;
}
For option 2, the content of the requested element at row,col is found like this:
private String getElement(int row, int col) {
String result = null;
String query = "SELECT * from A where row=? and col=?";
try {
PreparedStatement preps = con.prepareStatement(query);
preps.setInt(1, row);
preps.setInt(2, col);
preps.execute();
rs = preps.getResultSet();
if (rs.next()) {
result = rs.getString("content");
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return result;
}
It is obvious that option 1 is accessing elements faster. Option 2 saves database space.
PS: If you have an array of arrays of varying length option 1 will not work.
colNumber is the fixed number of columns of your String array.