如何检查 table 中是否已经存在索引?

How to check if an index already exists in a table?

我有这个方法来检查 table 中是否已经存在索引。 查询 returns a table 像这样

如何检查 table 列中是否已有一行 Key_name?

 private boolean checkIndexExists(JdbcConnection connection,String indexName,String tableName) throws DatabaseException, SQLException {
        boolean exists=false;

        String searchStatement = "SHOW INDEXES FROM "+tableName;
        ResultSet columnsRs;
        Statement s = connection.createStatement();
        columnsRs = s.executeQuery(searchStatement);
        
        //CHECK IF THE INDEX ALREADY EXISTS

        return exists;
    }

一种方法是遍历结果集。您可以遍历 table 的所有行并检查 Key_name 的值是否等于 indexName.

private boolean checkIndexExists(
    final JdbcConnection connection,
    final String indexName,
    final String tableName
) throws DatabaseException, SQLException {
    final String searchStatement = "SHOW INDEXES FROM " + tableName;
    final Statement statement = connection.createStatement();
    final ResultSet resultSet = statement.executeQuery(searchStatement);

    while (resultSet.next()) {
        if (indexName.equals(resultSet.getString("Key_name"))) {
            return true;
        }
    }
    return false;
}

不要使用显示。这意味着显示简单的结果,并不适合任何类型的决策或计算。

使用次数:

private boolean checkIndexExists(Connection connection,String indexName,String tableName) throws SQLException {
    String stmt = "SELECT COUNT(Key_name) FROM "+tableName+" WHERE Key_name='"+indexName+"'";
    try(ResultSet rs = connection.createStatement().executeQuery(stmt);){
        return rs.getInt("COUNT") > 0;
    }
}

SQL COUNT returns NULL 如果没有行可计数,但 getInt 将 NULL 解释为 0,因此我们不需要以这种方式检查 NULL。另外,请注意 ResultSet 是一种资源,应该在 try-catch-finally 或(首选)try-with-resources 中关闭,如此处所示。

根据您的操作,仅 return 索引可能更有用:

private int getCurrentIndex(Connection connection,String indexName,String tableName) throws SQLException {
    String stmt = "SELECT MAX(Seq_in_index) FROM "+tableName+" WHERE Key_name='"+indexName+"'";
    try(ResultSet rs = connection.createStatement().executeQuery(stmt);){
        return rs.getInt("MAX");
    }
}

SQL 中也有 EXISTS 关键字,但它通常在较大的语句中使用,对于这种用例来说会更复杂。但是,如果您尝试插入新行并相应地设置 Seq_in_index,则可以使用 EXISTS 在一个事务中完成所有操作。