Mee Mee - 1 year ago 75
SQL Question

NullPointerException when using String from SQL database

I am trying to use a String read from a row in an SQL database, but when I do, I get the following NullPointerException :

Exception in thread "main" java.lang.NullPointerException
at ReadCol.main(

My code is shown below...

public String[] array;
ResultSet rs=st.executeQuery("select * from ATTENDANCE");

File file = new File("E:\\eclipse\\workspace\\AutoAttendanceSystem\\res\\AttendanceData.csv");
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
array = line.split(",");
if(rs.getString(1).equals(array[0]) && rs.getString(7).equals(array[6])){
JOptionPane.showMessageDialog(null, "Can't Update Because record already exist");

What is the problem ?

Answer Source

It appears that the problem is when you call rs.getString(7).equals(...) : a NULL value must have been stored in the 7th column, and getString(7) returns null, which is why calling equals on null throws an exception.

It could as well be on the first column too. If you want to know, separate the conditions on 2 lines and see which one throws an exception :

if(rs.getString(1).equals(array[0]) && 

If it is ok for your database to hold NULL values, then what you should do, is test for it before applying equals :

if( ( rs.getString(1) == null && array[0] == null // or "" if you prefer
    || rs.getString(1) != null && rs.getString(1).equals(array[0]) )
    && ... // same for 7th column

To make it cleaner :

String databaseResult1, databaseResult2, fileResult1, fileResult2;

databaseResult1 = rs.getString(1);
fileResult1 = array[0];
databaseResult2 = rs.getString(7);
fileResult2 = array[6];

    ( databaseResult1 == null && fileResult1 == null 
      || databaseResult1 != null && databaseResult1.equals(fileResult1) )
    ( databaseResult2 == null && fileResult2 == null 
      || databaseResult2 != null && databaseResult2.equals(fileResult2) )

By the way, you are not comparing a String to an Array, you are comparing two Strings (which is the right thing to do)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download