简体   繁体   中英

How do I determine retrieved value type in Java?

Having searched unsuccessfully for days, I thought I would ask.

I am retrieving a value from a table, whose columns are all varchar. How do we go about identifying the type of value. For eg

accountnumber may have values such as 123456 , 123456:78910

    ...
    try(ResultSet rs = stmt.executeQuery("select * from table")){
      if(rs.next()){
        //Cannot use anything other than 'getString'
        String var = rs.getString("accountnumber");                 
        //Determine if var is an Integer
        System.out.println(var instanceof Integer)  //returns false because 'var' is of type String.
      }
    }
   ...

Any pointers are much appreciated.

The thing works as intended. The columns are typed as varchar in the schema, so the database and the Java SQL interface can't know if you actually have numbers or names or dates or whatever stored inside. Only getString should work.

It's up to you to try to parse the string results in ways that make sense.

For example, the Integer.parseInt method would transform a string to an integer, or throw an exception if it cannot. There's equivalent versions for Long or Double etc.

However, looking at the example accountnumbers, they aren't really integers, but rather have a more complex structure. You might want to model that with a class with two fields (primaryAccountNumber, theOtherAccountNumber) etc, and it should take care of parsing.


On a different note, you should never select * from a database, but rather be explicit about the fields that you need. This protects against schema changes which remove fields you were dependent on (the select will fail, instead of some code later down the line), or pulling in too much data and just using a bit of it.

ResultSet#getMetaData(); will give you the required informations. ResultMetaData has some methods that will help eg. getColumnType(int) or getColumnClassName(int)

You can use pattern matching to check its a number or a string.

  String var = rs.getString("accountnumber");
  Matcher ss1 = Pattern.compile("([0-9]*)").matcher(var);
  if (ss1.matches()) {
      // its a number
  } else {
      // its a string
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM