java 如何在准备好的语句中将列表对象转换为 bigdecimal?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13175623/
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 convert a list object to bigdecimal in prepared statement?
提问by Srikanth Sridhar
I am using prepared statement for bulk insertion of records. Iam iterating a list which contains values and their dataTypes differ. One of the data type is BigDecimal and when i try to set calling preparedstatement, it is throwing null pointer exception.
我正在使用准备好的语句来批量插入记录。我正在迭代一个包含值且它们的数据类型不同的列表。其中一种数据类型是 BigDecimal,当我尝试设置调用 Preparedstatement 时,它抛出空指针异常。
My code
我的代码
int count = 1;
for (int j = 0; j < list.size(); j++) {
if(list.get(j) instanceof Timestamp) {
ps.setTimestamp(count, (Timestamp) list.get(j));
} else if(list.get(j) instanceof java.lang.Character) {
ps.setString(count, String.valueOf(list.get(j)));
}
else if(list.get(j) instanceof java.math.BigDecimal) {
ps.setBigDecimal(count, (java.math.BigDecimal)list.get(j));
} else {
ps.setObject(count, list.get(j));
}
count++;
}
I tried 2 ways to convert, casting the object and tried to create a new object of type BigDecimal
我尝试了 2 种转换方法,转换对象并尝试创建一个 BigDecimal 类型的新对象
ps.setBigDecimal(count, new BigDecimal(list.get(j).toString));
both donot solve my problem. It is throwing null pointer exception.
两者都不能解决我的问题。它正在抛出空指针异常。
help is appreciated.
帮助表示赞赏。
Thanks
谢谢
回答by efirat
Here is a solution I found, it seems to be useful for all kind of Object to primitive types.
这是我找到的一个解决方案,它似乎对所有类型的 Object 到原始类型都有用。
public static BigDecimal getBigDecimal( Object value ) {
BigDecimal ret = null;
if( value != null ) {
if( value instanceof BigDecimal ) {
ret = (BigDecimal) value;
} else if( value instanceof String ) {
ret = new BigDecimal( (String) value );
} else if( value instanceof BigInteger ) {
ret = new BigDecimal( (BigInteger) value );
} else if( value instanceof Number ) {
ret = new BigDecimal( ((Number)value).doubleValue() );
} else {
throw new ClassCastException("Not possible to coerce ["+value+"] from class "+value.getClass()+" into a BigDecimal.");
}
}
return ret;
}
here is the link: http://www.java2s.com/Code/Java/Data-Type/ConvertObjecttoBigDecimal.htm
这是链接:http: //www.java2s.com/Code/Java/Data-Type/ConvertObjecttoBigDecimal.htm