How to set Float PreparedStatement (jdbc) to NULL

I want to add a lot of data to my database using a Java program. I am trying to control the fact that the String value may be empty, so I want to set to null.

This does not work ( 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 this is normal because we cannot set the float to null, but in PostgreSQL I can set the numeric column to null.

How can i do this?

+4
source share
3 answers

setFloat throws NullPointerException, float, float. setObject - null, . - :

pstm.setObject(3, tabChaine[9].isEmpty() ? null : Float.valueOf(tabChaine[9]), java.sql.Types.FLOAT);
+1

:

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);
}

setNull()

+1

You should use setNull () if you need to set the null parameter

0
source

Source: https://habr.com/ru/post/1691654/


All Articles