private boolean indexExists ( String table , String indexName ) throws SQLException { PreparedStatement statement = null ; ResultSet result = null ; try { statement = this . connection . prepareStatement ( "SHOW INDEX FROM " + table + " WHERE Key_name!= 'PRIMARY'" ) ; result = statement . executeQuery ( ) ; // Check if an index exists (because otherwise the query would // be awfully slow. Note that the existence of ANY index will // suffice - we might want to check for a specific index. if ( result == null || ! result . next ( ) ) { return false ; } /* * SOME INDEX EXISTS! We can now check for the existence of a specific index */ if ( indexName != null ) { // go back to first result result . first ( ) ; // check all existing indexes for the specific index name boolean specificIndexExists = false ; while ( result . next ( ) ) { if ( result . getString ( 3 ) . equals ( indexName ) ) { specificIndexExists = true ; } } return specificIndexExists ? true : false ; } else { // we have an index, but don't want to check for an index with // a specific name return true ; } } finally { if ( statement != null ) { statement . close ( ) ; } if ( result != null ) { result . close ( ) ; } } }
Checks if an index with a specific name exists in a given table .