How to check if a table exists in MySQL

2

I already found several forms on the internet, but none of them the way I wanted it.

I would like a java method to check whether or not a table exists in the database, if it exists, return TRUE or return FALSE .

Thank you in advance.

Note: I'm not going to put any code, because the ones I found on the internet were very long and executed more than I wanted to (just test if it exists or not).

    
asked by anonymous 28.05.2016 / 04:24

1 answer

2

You can run an SQL query in MySQL using show tables and check if the query returned some result for the query using Java (which generates the more extensive codes).

show tables like 'MinhaTabela'

Or use metadata (Java) available:

/**
 *
 *  abre a conexão com o banco de dados
 */
Connection conexao = DriverManager.getConnection(URL, USUÁRIO, SENHA);

/**
 *
 *  acessa os metadados do banco de dados
 */
DatabaseMetaData metadados = conexao.getMetaData();

/**
 *
 *   verificar se a tabela existe
 */
ResultSet tabela = metadados.getTables(null, null, "MinhaTabela", null);

/**
 *
 *  condição, caso a tabela exista
 */
if (tabela.next()) {
  /**
   *
   *  faça algo se a tabela existir
   */
}
    
28.05.2016 / 04:49