2012-11-12 104 views
2

我有一个ResultSet,我遍历并创建了一个类似view(html)的报表。 问题是某些列返回Long值(作为SQL中的数学函数的结果)。如何确定一个字符串类型是双精度还是长精度

有没有一种简单的方法,我可以通过DataType来识别这个值?

可以说我想要做这样的事情

String x = rs.getString(1); 
if(MyUtilClass.isOfTypeLong(x)){ 
    //implement my bussiness logig 
} 

我已经看到了这个帖子How do you determine the type of data contained in a string?。如果现在没有更好的选择,我将继续使用regEx解决方案。

+0

这可能是你想要的答案:http://alvinalexander.com/java/edu/pj/jdbc/recipes /ResultSet-ColumnType.shtml –

+0

结果集元数据说什么?即MySQL以什么类型向您发送数据? rs.getMetadata()。getColumnType?在这里阅读更多信息:http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSetMetaData.html。它是以字符串形式发送,还是长时间发送,还是直接发送? –

+0

'Object x = rs.getObject(1);'然后'instanceof BigDecimal'等等。作为全部类getBigDecimal(1)'是值得一想的。 –

回答

5

为什么不尝试Long.valueOf(String)首先将其解析为Long,如果没有解析为DoubleDouble.valueOf(String)

如果字符串不能被解析,则抛出一个NumberFormatException

public static void main(String[] args) throws Exception { 
    final String s1 = "1234567890"; 
    System.out.println(isParsableAsLong(s1)); // true 
    System.out.println(isParsableAsDouble(s1)); // true 

    final String s2 = "1234.56789"; 
    System.out.println(isParsableAsLong(s2)); // false 
    System.out.println(isParsableAsDouble(s2)); // true 
} 

private static boolean isParsableAsLong(final String s) { 
    try { 
     Long.valueOf(s); 
     return true; 
    } catch (NumberFormatException numberFormatException) { 
     return false; 
    } 
} 

private static boolean isParsableAsDouble(final String s) { 
    try { 
     Double.valueOf(s); 
     return true; 
    } catch (NumberFormatException numberFormatException) { 
     return false; 
    } 
} 
+0

这真的很有帮助,谢谢 – MaVRoSCy

2

如果.可以用来区分则:

String number = "12345"; 
    if(number.indexOf(".")>=0){ 
     //decimal 
     Double doubleValue = Double.valueOf(number); 
    }else{ 
     Long longValue = Long.valueOf(number); 
    } 

带有异常处理功能:

String number = "12345"; 
    //You may define two variables as Double & Long (as used in previous example) 
    Number formattedNumber = null; 

    try{ 
     if(number.indexOf(".")>=0){ 
      //decimal 
      formattedNumber = Double.valueOf(number); 
     }else{ 
      formattedNumber = Long.valueOf(number); 
     } 
    }catch(NumberFormatException nfe){ 
     System.out.println("Not a double or Long"); 
    } 
0

试试这个

Long l=Long.parseLong(x); 

,如果它不能解析,然后它会通过在catch块异常尝试

Double=Double.parseDouble(x) 

即使如此,如果异常occurrs它不能被解析