4

I want to insert in my database lots of data with a Java program. I'm trying to manage the fact that the value of the String could be empty, in that way, I want to set the value to null.

This isn't working (pstm.setFloat...) :

PreparedStatement pstm;
try {
    pstm = connex.prepareStatement("INSERT INTO opfofa._produit_val_nut VALUES (?,?,?,?,?,?,?,?,?,?)");
    pstm.setInt(1,id);
    pstm.setString(2,tabChaine[8]);
    pstm.setFloat(3,tabChaine[9].isEmpty()? null:Float.valueOf(tabChaine[9]));
    ...
    pstm.executeUpdate();
}catch(PSQLException e) {
    System.out.println("already inserted : "+e);
}

Error : java.lang.NullPointerException and that is normal because we can't set a float to null but in PostgreSQL I can set a Numeric column to null.

How can I do this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cetelem
  • 67
  • 1
  • 10

3 Answers3

2

The code should look something like this:

PreparedStatement pstm;
try {
    pstm = connex.prepareStatement("INSERT INTO opfofa._produit_val_nut VALUES (?,?,?,?,?,?,?,?,?,?)");
    pstm.setInt(1,id);
    pstm.setString(2,tabChaine[8]);
    if (tabChaine[9].isEmpty()) {
        pstm.setNull(3, java.sql.Types.FLOAT);
    }
    else {
        pstm.setFloat(3,Float.valueOf(tabChaine[9]));
    }
    ...
    pstm.executeUpdate();
}catch(PSQLException e) {
    System.out.println("already inserted : "+e);
}

More info on setNull()

clinomaniac
  • 2,200
  • 2
  • 17
  • 22
2

setFloat throws NullPointerException because it expects primitive float and not a Float object. You can try using setObject method instead - it allows using null values if needed. Something like:

pstm.setObject(3, tabChaine[9].isEmpty() ? null : Float.valueOf(tabChaine[9]), java.sql.Types.FLOAT);
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
0

You have to use setNull() if you need to set a parameter null

TheOni
  • 810
  • 9
  • 26