java check if sql table exists

java check if sql table exists

To check if a table exists in a SQL database in Java, you can use the DatabaseMetaData class to retrieve metadata about the database, and then use the getTables method to retrieve a list of all the tables in the database. You can then iterate through the list of tables and use the getTableName method to check if the table you are interested in exists.

Here's an example of how to use the DatabaseMetaData class to check if a table exists in a SQL database:

‮ refer‬to:lautturi.com
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
  public static void main(String[] args) {
    Connection conn = null;
    try {
      // connect to the database
      conn = getConnection();
      DatabaseMetaData meta = conn.getMetaData();

      // get a list of all tables in the database
      ResultSet tables = meta.getTables(null, null, null, new String[] {"TABLE"});
      while (tables.next()) {
        // check if the table exists
        if (tables.getString("TABLE_NAME").equalsIgnoreCase("table_name")) {
          // table exists
          break;
        }
      }
    } catch (SQLException e) {
      // handle SQL exception
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e) {
          // handle SQL exception
        }
      }
    }
Created Time:2017-11-03 00:14:49  Author:lautturi