Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a mysql decimal value in java prepared statement?

How to set decimal value in java prepared statement. I was tried as follows

My table query

create table A (x decimal(22,0))

In java I tried to set it as

preperedStatmentObj.setLong(1,aLongValue);

But i am getting the following error

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

Thank you

like image 330
Java_Dinesh Avatar asked Jan 07 '13 11:01

Java_Dinesh


People also ask

How do you declare a decimal in Java?

In Java, we have two primitive types that represent decimal numbers – float and decimal: double myDouble = 7.8723d; float myFloat = 7.8723f; The number of decimal places can be different depending on the operations being performed. In most cases, we're only interested in the first couple of decimal places.

How do you store decimal values in a database?

For Example − DECIMAL(4,2), it means you can take 4 digits total and 2 digit after decimal point. The second parameter is up to 2 digit after decimal point. Case 1 − 12.34 is valid. Case 2 − 123.4 is not valid.

How are decimals stored in Java?

A float data type in Java stores a decimal value with 6-7 total digits of precision. So, for example, 12.12345 can be saved as a float, but 12.123456789 can't be saved as a float. When representing a float data type in Java, we should append the letter f to the end of the data type; otherwise it will save as double.


1 Answers

Try using setBigDecimal

BigDecimal d = new BigDecimal(aLongValue);
preperedStatmentObj.setBigDecimal(1, d);
like image 108
John Woo Avatar answered Sep 28 '22 11:09

John Woo