Link to home
Start Free TrialLog in
Avatar of gironszeg
gironszeg

asked on

JDBC - how to avoid null pointer exceptions on NULL fields

I am using the following method in a database class which I pass an SQL string into. It in turn fills a Vector of rows each element of which is a vector containing individual field values. This works fine until I encounter NULL fields in the database when null pointer exceptions occur. I have tried catching them but it still doesn't recover and continue.
How should I alter this code (or if someone had code to do what I want that would be great)
Thanks
gironszeg

      public void executeQuery(String sQuery){//For result returning SQL statements      
            this.theQuery = sQuery;
            ResultRows = new Vector();
            try
            {
              Statement queryStatement = databaseConnection.createStatement();
              ResultSet theResults = queryStatement.executeQuery(theQuery);
              ResultSetMetaData rsmeta = theResults.getMetaData();

              int numColumns = rsmeta.getColumnCount();
              String resultsText = new String("");
              while(theResults.next())
              {
                numRows++;
                  Cols = new Vector();
                  for(thisCol = 1; thisCol <= numColumns; thisCol++){
                        resultsText = theResults.getString(thisCol).trim();
                        Cols.addElement(resultsText);
                  }
                  ResultRows.addElement(Cols);
              }
            }
            catch(SQLException sqle)
            {
              System.out.println(sqle.toString());
            }      
      }
Avatar of jerch
jerch

change
resultsText = theResults.getString(thisCol).trim();

to
resultsText = theResults.getString(thisCol);

if (resultText != null)
 resultText = resultText.trim();
else
 resultText = <what do you want to assign for a null value probably "">;

Hope this solved your problem

cheers...
Jerson
ASKER CERTIFIED SOLUTION
Avatar of pagladasu
pagladasu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial