实际上我的整个问题都在标题中。我有一个管理我的发票对象到我的 Sqlite 数据库的插入和删除的类。
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,它会引发异常...有人可以告诉我为什么吗? ? 感谢您到目前为止的帮助...
最佳答案
看PreparedStatement.setFloat()
的签名:
void setFloat(int parameterIndex, float x) throws SQLException
如您所见,它使用原始类型 float
而不是包装类型 Float
,因此您不能将 null
传递给它。尝试将 Float
类型的 null
值转换为 float
会导致 NullPointerException
。
String
是引用类型,因此您可以将 null
传递给 PreparedStatement.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);
}
}
关于java PreparedStatement.setFloat 抛出 NullpointerException,允许 Pstmt.setString 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15988495/