NUMBER(10,2) in oracle database

Inside oracle database variable data type is NUMBER(10,2). So I need to get this value inside my java code. I tried with different ways:

  • Float
  • float
  • double
  • Double
  • BigDecimal

But these thing not mapping in java. What I need to do. Thanks in advance.

3 answers

  • answered 2018-11-08 07:45 user7294900

    Use ResultSet.getBigDecimal(int) to get by index

    or ResultSet.getBigDecimal(String) to get by column name

    This is also recommended in JDBC Guide for any Numeric type

    JDBC Types Mapped to Java Types

    NUMERIC java.math.BigDecimal

  • answered 2018-11-08 07:53 ace

    Check out this link Data Type and Java-to-Java Type Mappings.

    NUMBER is mapped to java.math.BigDecimal

    For 2 numbers after comma you can set:

    new BigDecimal(dbValue).setScale(2, RoundingMode.HALF_UP);
    

  • answered 2018-11-08 07:58 Carlos Heuberger

    You can use double or BigDecimal.

    Example, assuming table ATEST with column N defined as CREATE TABLE ATEST ( N NUMBER(10,2) ):

    import java.math.BigDecimal;
    import java.sql.DriverManager;
    
    import javax.swing.JOptionPane;
    
    public class OraNum {
        private static String url = "jdbc:oracle:thin:@localhost:1523:sid";
        private static String user = "User";
    
        public static void main(String[] args) throws Exception {
            var pwd = JOptionPane.showInputDialog("Password: ");
            if (pwd == null) {
                return;
            }
    
            try (
                    var conn = DriverManager.getConnection(url, user, pwd);
                    var stmt = conn.prepareStatement("select N from ATEST");
                    var rset = stmt.executeQuery();
                    ) {
                while (rset.next()) {
                    double d = rset.getDouble(1);
                    BigDecimal big = rset.getBigDecimal(1);
                    System.out.printf("double: %s,  BigDecimal: %s%n", d, big);
                }
            }
        }
    }
    

    You could also use rset.getObject() to get an Object. Checking its class you will see what the driver returns for that type (BigDecimal here); getDouble() just converts it to double - this may cause some precision lost, so is is probably better to use BigDecimal. (same true for getInt)

    Note: rset.getString() would also work, returning the textual representation (String) of the number.