【发布时间】:2015-06-19 10:06:56
【问题描述】:
我正在尝试检查表是否为空。我编写了这个方法:
public boolean checkIfNULL()
throws SQLException, ClassNotFoundException {
boolean flag=false;
System.out.println("Checking if table is empty...");
String sq = "select count(*) from TABLE1";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
PreparedStatement stm = c.prepareStatement(sq);
int rowsAffected = stm.executeUpdate();
if(rowsAffected == 0)
flag=true;
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null) {
stm.close();
}
if (c != null) {
c.close();
}
}
return flag;
}
但是某事正在发生,我收到一条错误消息 查询返回结果
Exceptionn: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
如何查看check的返回值?
更新 1:
除了上面的查询,我还尝试了SELECT EXISTS(SELECT 1 FROM TABLE1)
但同样的事情正在发生..
更新 2: 我用这个:
ResultSet rs = stm.executeQuery();
if(!rs.next())
flag=true;
else
System.err.println("ERROR - The table has records...");
它会打印出ERROR - "The table has records..."。这怎么可能?我通过 SQLite 管理器看到表,它是空的!
【问题讨论】:
-
我建议不要这样做。通常,我会推荐某种形式的
EXISTS,但我认为SQLite 不支持——但我仍然建议使用LIMIT 1运行基本查询。如果您只关心“不存在行”和“至少存在一行”的情况,则无需强制引擎计算 每一 行。只要你看到任何行,你就知道答案了。 -
如果您发布异常,请包含完整的堆栈跟踪,它提供的信息可能有助于追踪原因。
标签: sqlite jdbc prepared-statement