首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法在数据库中插入值,结果值超出了十进制/数值数据类型(3.1)的范围

无法在数据库中插入值,结果值超出了十进制/数值数据类型(3.1)的范围
EN

Stack Overflow用户
提问于 2021-03-31 18:41:00
回答 1查看 228关注 0票数 2

当我运行我的代码时,它甚至显示了以下错误:

java.sql.SQLDataException: The resulting value is out of range for the DECIMAL / NUMERIC data type (3.1).

我的Java文件:

代码语言:javascript
运行
复制
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);
        } 
    }
}

我可以输入所有的输入,但是最后,程序会显示上面的错误。我想把值插入到我的数据库中,只是这个错误让我感到不安。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-31 18:57:39

stmt.execute();太多了,而且确实可能导致“错误”错误。最后一个stmt = conexao.prepareStatement(sql);也是。

MySQL参考可能会有所帮助。十进制(3,1)的范围为-9.9 .9.9.这可能是一个正确的刻度,否则您可能打算使用十进制(5,2)

nota可能会被检查。

由于浮点(double)不精确,在java端使用BigDecimal (不动点)可能更好。

代码语言:javascript
运行
复制
        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);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66893494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档