杰瑞科技汇

Java中Oracle的Number类型如何高效处理?

Of course! The term "Java Oracle Number" can refer to a few different but related concepts. I'll break them down into the most common interpretations, from the most direct to the more contextual.

Java中Oracle的Number类型如何高效处理?-图1
(图片来源网络,侵删)

The Most Direct Answer: Handling Oracle NUMBER in Java JDBC

This is the most frequent meaning. When you connect a Java application to an Oracle database using JDBC, you need to handle Oracle's NUMBER data type correctly.

What is Oracle's NUMBER Type?

Oracle's NUMBER is a highly flexible and powerful data type that can store integer and floating-point numbers. It has two key components:

  • Precision (p): The total number of digits. For example, NUMBER(10, 2) can hold up to 10 digits in total.
  • Scale (s): The number of digits to the right of the decimal point. For example, NUMBER(10, 2) can store a number like 90.

The special case NUMBER(p) with no scale is used for integers. NUMBER without any precision or scale constraints can store numbers of virtually any magnitude.

How to Handle it in Java JDBC

In JDBC, the Oracle NUMBER type is mapped to Java's java.math.BigDecimal. This is the correct and recommended way to handle it for precision-critical applications like financial calculations.

Java中Oracle的Number类型如何高效处理?-图2
(图片来源网络,侵删)

Why BigDecimal and not Double?

  • Precision: double (and float) are binary floating-point types. They cannot precisely represent many decimal fractions (e.g., 0.1). This leads to rounding errors. BigDecimal stores numbers in decimal format, preserving exact precision.
  • Scale: BigDecimal allows you to explicitly control the number of decimal places, which is essential for monetary values.

Example: Java Code for Reading and Writing NUMBER

Let's look at a complete, runnable example using JDBC.

Database Table Setup

First, let's create a table in Oracle with a NUMBER column.

CREATE TABLE products (
    id          NUMBER(10) PRIMARY KEY,
    name        VARCHAR2(100),
    price       NUMBER(10, 2), -- For prices with cents
    quantity    NUMBER(5)      -- For whole numbers
);

Java JDBC Code

This code demonstrates inserting a record with a BigDecimal and reading it back.

Java中Oracle的Number类型如何高效处理?-图3
(图片来源网络,侵删)
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class OracleNumberExample {
    // Replace with your Oracle DB connection details
    private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
    private static final String USER = "your_username";
    private static final String PASS = "your_password";
    public static void main(String[] args) {
        // Use try-with-resources to ensure connections are closed automatically
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            System.out.println("Connection to Oracle DB successful!");
            // --- Example 1: Inserting data into a NUMBER column ---
            insertProduct(conn, 101, "Laptop", new BigDecimal("1200.50"), 5);
            insertProduct(conn, 102, "Mouse", new BigDecimal("25.99"), 50);
            // --- Example 2: Reading data from NUMBER columns ---
            getProducts(conn);
        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
        }
    }
    private static void insertProduct(Connection conn, int id, String name, BigDecimal price, int quantity) throws SQLException {
        String sql = "INSERT INTO products (id, name, price, quantity) VALUES (?, ?, ?, ?)";
        // Using PreparedStatement to prevent SQL injection and handle types
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.setString(2, name);
            pstmt.setBigDecimal(3, price); // The key method for NUMBER type
            pstmt.setInt(4, quantity);
            pstmt.executeUpdate();
            System.out.println("Inserted product: " + name);
        }
    }
    private static void getProducts(Connection conn) throws SQLException {
        String sql = "SELECT id, name, price, quantity FROM products";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            System.out.println("\n--- Product List ---");
            while (rs.next()) {
                // Use getBigDecimal for NUMBER columns
                BigDecimal price = rs.getBigDecimal("price");
                int quantity = rs.getInt("quantity"); // getInt() also works for NUMBER(p,0)
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.printf("ID: %d, Name: %s, Price: $%s, Quantity: %d%n",
                        id, name, price.toPlainString(), quantity);
            }
        }
    }
}

Key JDBC Methods:

  • preparedStatement.setBigDecimal(int parameterIndex, BigDecimal x): Used to set a NUMBER parameter in a PreparedStatement.
  • resultSet.getBigDecimal(String columnLabel): Used to retrieve a NUMBER column value as a BigDecimal.

Other Interpretations of "Java Oracle Number"

a) Oracle's JDBC Driver Version (ojdbc.jar)

Sometimes people refer to the Oracle JDBC driver itself as "Oracle Number" or "Oracle JDBC Number". The driver is a JAR file (e.g., ojdbc8.jar, ojdbc11.jar) that contains the implementation for connecting Java to Oracle databases.

  • Where to get it: Oracle JDBC Drivers Downloads
  • How to use it: You must add this JAR file to your project's classpath. In Maven, you would use a dependency like:
    <dependency>
        <groupId>com.oracle.database.jdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>19.3.0.0</version>
    </dependency>

b) The java.sql.Types Constant

In the JDBC API, java.sql.Types defines an integer constant for each SQL data type. The Oracle NUMBER type is mapped to Types.NUMERIC.

import java.sql.Types;
int oracleNumberType = Types.NUMERIC; // This is the constant for NUMBER

You might see this used in metadata queries or when dealing with ResultSetMetaData to determine the type of a column.

c) The java.lang.Number Class

java.lang.Number is the superclass for all Java numeric wrapper classes (Integer, Double, Float, Long, BigDecimal, BigInteger). It's an abstract class that provides methods for converting between different numeric types.

While BigDecimal is the specific type for Oracle NUMBER, Number is the more general parent class. Some APIs might accept Number as a generic input, but for database interaction, you should almost always use the specific, correct type (BigDecimal for NUMBER).

Summary

Context Meaning Key Java Class/API
Data Handling How to read/write Oracle's NUMBER type from/to Java. java.math.BigDecimal
JDBC API The constant representing the NUMBER type. java.sql.Types.NUMERIC
Project Setup The library (JAR file) that enables the connection. ojdbcX.jar (Maven/Gradle dependency)
Java Hierarchy The parent class for all Java number objects. java.lang.Number (abstract)

In short: When working with Oracle's NUMBER column in Java via JDBC, always use java.math.BigDecimal for maximum accuracy and reliability.

分享:
扫描分享到社交APP
上一篇
下一篇