Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL DECIMAL to Java Number

Tags:

java

mysql

jdbc

I have a database (MySQL 5.6 if it matters) in which I would like to store numeric values that will usually, but not always, be integers. Right now I have a DECIMAL(10, 3) column which seems to be working well. What I'm looking for is a method I know doesn't exist in native JDBC, but would be something like:

public Number ResultSet.getNumber()

which would return me a Long (or maybe even Integer) if the underlying SQL value is actually an integer, and a Double otherwise. Is there some way to get an equivalent result from an SQL DECIMAL column in JDBC?

like image 249
Dan Avatar asked Feb 29 '16 14:02

Dan


2 Answers

The recommended Java mapping for SQL DECIMAL and NUMERIC values is BigDecimal:

ResultSet.getBigDecimal()
like image 104
Misa Lazovic Avatar answered Sep 29 '22 16:09

Misa Lazovic


You can get decimal value from the table and convert it into Double as:

BigDecimal res = ResultSet.getBigDecimal();
like image 44
FallAndLearn Avatar answered Sep 29 '22 15:09

FallAndLearn