【发布时间】: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,因此每当向表中插入记录时,它都会自动递增。
【问题讨论】:
-
异常实际上是关于“列数”而不是“行数”