When I run my code, It works even shows this error:
java.sql.SQLDataException: The resulting value is out of range for the DECIMAL / NUMERIC data type (3.1).
My Java file:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Aula4 {
public static void main (String[] args) throws ClassNotFoundException, SQLException {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
String url = "jdbc:derby://localhost:1527/sistema_academico";
String usuario = "app";
String senha = "app";
Connection conexao;
Scanner ler = new Scanner(System.in);
conexao = DriverManager.getConnection(url, usuario, senha);
int id_aluno;
double nota;
String nome = null;
System.out.println("Welcome, type your id: ");
id_aluno = ler.nextInt();
System.out.println("Now, do you need to type your name: ");
nome = ler.next();
System.out.println("And finally, type your grade: ");
nota = ler.nextDouble();
String SQL_Update = "UPDATE aluno set NOTA=? WHERE id_aluno=?";
String sql = "insert into aluno " +
"(id_aluno,nome, nota) " +
"values (?,?,?)";
PreparedStatement stmt = conexao.prepareStatement(sql);
stmt.setInt(1, id_aluno);
stmt.setString(2, nome);
stmt.setDouble(3, nota);
stmt.executeUpdate();
stmt.execute();
stmt.close();
System.out.println("Accomplished!!");
stmt = conexao.prepareStatement(sql);
}
catch (SQLException ex){
System.out.println("Conection failed!"+ex);
}
}
}
I can type all inputs, but in the end, the program displays the error above. I want to insert values into my database, just this error It's disturbing me.
stmt.execute();
is too much, and indeed might have caused an "erroneous" error.
The last stmt = conexao.prepareStatement(sql);
too.
The MySQL reference might help. DECIMAL(3, 1) has range -9.9 .. 9.9. This might a correct scale, otherwise you maybe intended DECIMAL(5, 2).
nota
might be checked.
As floating point (double
) is imprecise, it might even be better to use BigDecimal
(fixed point) on java side.
System.out.println("And finally, type your grade: ");
BigDecimal bdnota = ler.nextBigDecimal();
// Check input: scale and digits
System.out.println("Scale: " + bdnota.scale());
stmt.setBigDecimal(3, bdnota);