Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java PreparedStatement.setFloat throws NullpointerException, Pstmt.setString ist allowed?

Actually my whole Question ist in the Title. I have a Class that manages the inserts and deletings of my Invoice-Objects to my Sqlite DB.

public class Invoice {
    private String str1;
    private Float flt1;
    private String str2Null;
    private Float flt2Null;

    public Invoice(String str1, Float flt1){
        this.str1 = str1;
        this.flt1 = flt1;
   }

  getters & setters...
}


public class InvoiceManager{
    ...Konstruktor...

    public int insertInvoice(Invoice invoice) throws Exception{
        try {
             PreparedStatement stmt = databaseConnection.prepareStatement(
            "INSERT INTO invoice (str1, flt1, str2Null, flt2Null) VALUES (?,?,?,?)");
             stmt.setString(1, invoice.getStr1());
             stmt.setFloat(2, invoice.getFlt1());
             stmt.setString(3, invoice.getStr2Null());
             stmt.setFloat(4, invoice.getFlt2Null());
     ....

So when I want to insert sth to the DB and Str2Null = null, it works and it write NULL to the sqliteDB, but with the Flt2Null = null, it raises an exception... can anybody say to me why??? Thanks for helping so far...

like image 414
unicorn Avatar asked Dec 12 '22 15:12

unicorn


1 Answers

Look at the signature of PreparedStatement.setFloat():

void setFloat(int parameterIndex, float x) throws SQLException

As you can see, it uses primitive type float instead of wrapper type Float, therefore you cannot pass null to it. Attempt to convert null value of type Float to float causes NullPointerException.

String is a reference type, therefore you can pass null to PreparedStatement.setString().

So, in the case of setFloat() you have to check for null and use setNull() to pass it:

public static void setFloatOrNull(PreparedStatement ps, int index, Float value) {
    if (value == null) {
        ps.setNull(index, Types.FLOAT);
    } else {
        ps.setFloat(index, value);
    }
}
like image 162
axtavt Avatar answered Dec 28 '22 23:12

axtavt