【问题标题】:SQLException "discrepancy in the number of rows counted" when trying to execute an INSERT query尝试执行 INSERT 查询时出现 SQLException“计数的行数差异”
【发布时间】:2015-10-18 20:15:06
【问题描述】:

我正在尝试向表中插入一些值,但在 Java 控制台中显示 SQLException,提示“计数的行数有差异”。

代码如下。

public static int enviaMensaje(int id_destinatario, String mensaje) throws Exception{
    PreparedStatement ps = null;        
    Connection con = null;

    int id_insertado = 0;

    try {

        String SQL_DRV = "org.hsqldb.jdbcDriver";
        String SQL_URL = "jdbc:hsqldb:hsql://localhost/";

        Class.forName(SQL_DRV);
        con = DriverManager.getConnection(SQL_URL, "sa", "");
        ps = con.prepareStatement("insert into public.mensaje values(?, ?)",
                Statement.RETURN_GENERATED_KEYS);

        ps.setInt(1, id_destinatario);
        ps.setString(2, mensaje);

        int updated = ps.executeUpdate();
        if (updated != 1) {
            throw new Exception("[ALREADY PERSISTED]");
        } 

        if (updated == 1) {
            ResultSet generatedKeys = ps.getGeneratedKeys();
            if (generatedKeys.next()) {
                id_insertado = generatedKeys.getInt(1);
            }
        }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        try {
            throw new Exception("Driver not found", e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        try {
            throw new Exception("Invalid SQL or database schema", e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception ex) {
            }
        }
        ;
        if (con != null) {
            try {
                con.close();
            } catch (Exception ex) {
            }
        }
        ;
    }
    return id_insertado;
}

该表具有列... ID、ID_RECEIVER 和 CONTENT。 ID 是带有“IDENTITY”关键字的 PK,因此每当向表中插入记录时,它都会自动递增。

【问题讨论】:

  • 异常实际上是关于“列数”而不是“行数”

标签: java sql hsqldb


【解决方案1】:

您需要指定列,因为您没有为所有列提供值。

 ps = con.prepareStatement("insert into public.mensaje(id_receiver, content) values(?, ?)",
                Statement.RETURN_GENERATED_KEYS);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2014-10-14
    • 2013-09-21
    • 1970-01-01
    相关资源
    最近更新 更多