我想知道如何发出MySQL命令,该命令检查数据库中的表是否为空,然后将布尔结果存储到java变量中。我正在尝试使用JDBC命令来执行此操作。这是我到目前为止的内容,但无法正常工作:
@Override
public boolean isEmpty(Connection connection) {
Statement statement = null;
ResultSet resultSet = null;
Boolean var = true;
try {
statement = connection.createStatement();
System.out.println(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons) AS OUTPUT"));
if(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons)")) {
var = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return var;
}
当我使用全新的未填充的mySQL表运行程序时,该函数返回true。有人知道解决方案吗?
您的测试将检查该表是否存在,而您想查看该表是否包含任何行。为此,请从表中选择行数并验证其是否大于0
。优先使用PreparedStatement
而不是PreparedStatement
(效率和性能更高),并且您实际上需要从服务器迭代Statement
来迭代结果。类似,
ResultSet
将@Override
public boolean isEmpty(Connection connection) {
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean res = false; // no need for the wrapper type here.
String sql = "SELECT COUNT(*) FROM Persons";
try {
statement = connection.prepareStatement(sql);
System.out.println(sql);
resultSet = statement.executeQuery();
if (resultSet.next()) {
res = resultSet.getInt(1) > 0;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return res;
}
更改为var
,因为(从Java 10开始,res
现在是Java中的关键字。