4

实际上我的整个问题都在标题中。我有一个类来管理我的发票对象到我的 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());
     ....

因此,当我想将某事物插入数据库并且 Str2Null = null 时,它可以工作并将 NULL 写入 sqliteDB,但是在 Flt2Null = null 的情况下,它会引发异常......有人可以告诉我为什么吗???感谢您到目前为止的帮助...

4

1 回答 1

13

看签名PreparedStatement.setFloat()

void setFloat(int parameterIndex, float x) throws SQLException

如您所见,它使用原始类型float而不是包装类型Float,因此您不能传递null给它。尝试将null类型的值转换Floatfloat原因NullPointerException

String是引用类型,因此您可以传递nullPreparedStatement.setString().

因此,如果setFloat()您必须检查null并使用setNull()以通过它:

public static void setFloatOrNull(PreparedStatement ps, int index, Float value) {
    if (value == null) {
        ps.setNull(index, Types.FLOAT);
    } else {
        ps.setFloat(index, value);
    }
}
于 2013-04-13T14:07:18.257 回答