java 如果值为零,如何在准备好的语句中设置 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36136961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set null in prepared statement if the value is zero
提问by Gopinath
preparedStatement.setInt(1, pimDataVo.getItemFlashMessageId());
preparedStatement.setInt(2, pimDataVo.getErpImprintCodeId());
preparedStatement.setInt(3, pimDataVo.getPublisherCodeId());
preparedStatement.setInt(4, pimDataVo.getGlClassId());
Is there any way to set these values null, if the get values are zero.?? All are Number columns
如果获取值为零,有没有办法将这些值设置为空。??都是数字列
回答by Pablo Santa Cruz
Yes, you need to use setNull
method. So, in your case it would be:
是的,你需要使用setNull
方法。因此,在您的情况下,它将是:
if (pimDataVo.getItemFlashMessageId() != 0) {
preparedStatement.setInt(1, pimDataVo.getItemFlashMessageId());
} else {
// use setNull
preparedStatement.setNull(1, java.sql.Types.INTEGER);
}
And you use a similar approach for the other values. You could also write a HELPER CLASS to perform this if for you (so you don't repeat a lot of code). Something like this:
您对其他值使用类似的方法。如果适合您,您也可以编写一个 HELPER CLASS 来执行此操作(这样您就不会重复很多代码)。像这样的东西:
public static void setIntOrNull(PreparedStatement pstmt, int column, int value)
{
if (value != 0) {
pstmt.setInt(column, value);
} else {
pstmt.setNull(column, java.sql.Types.INTEGER);
}
}
Then you use your code like this:
然后你像这样使用你的代码:
Helper.setIntOrNull(preparedStatement, 1, pimDataVo.getItemFlashMessageId());
Helper.setIntOrNull(preparedStatement, 2, pimDataVo.getErpImprintCodeId());
Helper.setIntOrNull(preparedStatement, 3, pimDataVo.getPublisherCodeId());
Helper.setIntOrNull(preparedStatement, 4, pimDataVo.getGlClassId());