KONAKONA
KONAKONA

Reputation: 87

Loading resultset from JDBC into two-dimensional table

public void selectStudent() throws SQLException{
    try{
        con= this.getConnection();
        if(con!=null){
            // Create and execute an SQL statement that returns some data.
            String SQL = "SELECT * FROM dbo.Student";
            stmt = con.createStatement();
            rs = stmt.executeQuery(SQL);

            // Iterate through the data in the result set and display it.
            while (rs.next()) {
                for(int i=0;i<=5;i++){
                      data[rs.getRow()][i]=rs.getString(i+1);
                }
            }
            closeConnection();
        }else System.out.println("Error: No active Connection");
   }catch(Exception e){
        e.printStackTrace();
   }
}

I want to add my results from JDBC SQL query into a two-dimensional object array, for future use in Table (swingUI). Unfortunately, the code above doesnt work, and i dont know why - i get errors during saving my results into data object.

Error type i get is NullPointerException.

Upvotes: 0

Views: 985

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

I think you have an Object like this :

Object[][] data; 

For that you get an error NullPointerException because it is not initialized it so before you put your result in this Array you should to initialize it like this :

data = new String[numberOfRow][6];
while (rs.next()) {
  for(int i=0; i<=5; i++){
      data[rs.getRow()][i]=rs.getString(i+1);
  }
}

EDIT

Object[][] data = {{"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)}, 
            {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)}};

This make you work more and more to define the type of your attributes, so i suggest to you to create a new Type for example :

public class TypeObject {

    private String s1;
    private String s2;
    private String s3;
    private String i1;
    private boolean b1;

    public TypeObject(String s1, String s2, String s3, String i1, boolean b1) {
        this.s1 = s1;
        this.s2 = s2;
        this.s3 = s3;
        this.i1 = i1;
        this.b1 = b1;
    }

    //getters and setters
}

So instead to use and Object[][] use TypeObject[] and you can easily set or get your attributes like this :

TypeObject[] data = new TypeObject[numberRow];
TypeObject d = new TypeObject(rs.getString("c1"), rs.getString("c2"), rs.getString("c3"), rs.getInt("c4"), rs.getBoolean("c5"));

data[i] = d;

So the advantage of this way :

  • You can add a new column in your table, so easily you can add a new field in your TypeObject class
  • You can create constructor like you want.
  • and and

Upvotes: 1

Related Questions