-3

While running this code I get "JAVA error"

And in the console I see

  • Connection to db
  • Connection suceeded
  • Select * from project.user
  • 1
  • java.lang.NullPointerException
  • ...
  • ...
  • ...
  • java.lang.NullPointerException
public void showuser(){
  System.out.println("Connection to db");
    try {
            Connection con = DriverManager.getConnection(url, "", "");
            System.out.println("Connection suceeded");
            String sql = "Select * from project.user";
            System.out.println(sql);
            Statement st = con.createStatement();
            ResultSet rs= st.executeQuery(sql);
            String title[]={"ID","Name","Status","Nomber","Balance","Login","Password"};
            DefaultTableModel aModel = new DefaultTableModel();
            aModel.setColumnIdentifiers(title);
            int i=0;
            while (rs.next())
            {   Object objects[]= new Object[7];
                i=0;
                while(i<7)
                {
                objects[i]=rs.getObject(i+1);
                System.out.println(objects[i].toString());
                i++;
                }
                aModel.addRow(objects);
           }
           jTable1.setModel(aModel);
           con.close();
    }    
    catch (SQLException ex)
        {
           while(ex!= null)
           {
             ex=ex.getNextException();
           }
           JFrame f1= new JFrame();
           JOptionPane.showMessageDialog(f1,"SQL error");
                            System.out.println(ex);
        }
    catch (java.lang.Exception ex)
        {
            ex.printStackTrace();
            JFrame f1= new JFrame();
            JOptionPane.showMessageDialog(f1,"JAVA error");
                                            System.out.println(ex);
        }
}
Garry
  • 3
  • 4

1 Answers1

0

I don´t know if thats the problem since the last time i worked with ResultSets was quite a time ago but you you rs.getObject(i+1)...if getObject() just returns the column values you are going above the index (7 columns (max index = 6) but you go to 6+1 in your while(i < 7 loop) because of the i+1. If the bevhaviour ob getObject is then that it returns null if it contains no value at the given index you will get a NullPointer at objects[i].toString() i hope this helps you EDIT as MadProgrammer pointed out my assumption regarding the index of the ResultSet was false. Just ignore this answer

Abbel
  • 320
  • 1
  • 9
  • 1
    JDBC is 1 indexed, unlike Java arrays (and otherwise in general) which is 0 indexed – MadProgrammer Feb 20 '15 at 06:31
  • ah ok i will edit my answer to mark it as false. Like i said it has been quite a time but thanks for clearing things up :) – Abbel Feb 20 '15 at 06:37