Java如何获取列的精度和小数位值?
例如,您在数据库表中有一个数字或双精度类型的列,并且您想要获得该列的精度和小数位数。这是给你的例子。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class ScaleAndPrecisionExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { Statement statement = connection.createStatement(); String query = "SELECT id, quantity, price FROM order_details"; ResultSet resultSet = statement.executeQuery(query); ResultSetMetaData metadata = resultSet.getMetaData(); int precision = metadata.getPrecision(3); int scale = metadata.getScale(3); System.out.println("Precision: " + precision); System.out.println("Scale : " + scale); } catch (SQLException e) { e.printStackTrace(); } } }
结果:
Precision: 10 Scale : 2
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>