SQLException"计算的行数差异"尝试执行INSERT查询时

时间:2015-10-18 20:15:06

标签: java sql hsqldb

我试图在表中插入一些值,但是在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。关键字,因此只要将记录插入表中,它就会自动增加。

1 个答案:

答案 0 :(得分:0)

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

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