How to check if a table exists in Mysql

Asked

Viewed 1,692 times

2

I’ve found several ways on the Internet, but none the way I wanted.

I would like a java method for which it checks whether a table exists in the database if it exists TRUE or return FALSE.

Grateful from now on.

Note: I will not put any code, because the ones I found on the Internet were very extensive and ran more than I wanted (just test whether or not it exists).

  • Thinking quickly on a method is very easy just do a select in the table if it contains lines in the same it will be true return true if not false. public Static Boolean checkNext() {} public Boolean checkNext(){}

1 answer

3


You can run an SQL query in Mysql using show Tables and check whether the query returned some result for the query using Java (which generates the most extensive codes).

show tables like `MinhaTabela`

Or use the 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
   */
}

  • Hello, could you explain a little about the function next() ??

  • This function serves to move the reading of the scanner in Java. By default, the scanner data is returned in token form, which generates blanks. The function next() will return the first non-empty token (true), which is the result of the metadata query or "the next query result". If there is no result, returns false, so the if

Browser other questions tagged

You are not signed in. Login or sign up in order to post.