Example usage for java.sql DatabaseMetaData getTables

List of usage examples for java.sql DatabaseMetaData getTables

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getTables.

Prototype

ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[])
        throws SQLException;

Source Link

Document

Retrieves a description of the tables available in the given catalog.

Usage

From source file:com.netflix.metacat.connector.jdbc.services.JdbcConnectorTableService.java

@Override
public boolean exists(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) {
    boolean result = false;
    try (Connection connection = this.dataSource.getConnection()) {
        final String databaseName = name.getDatabaseName();
        connection.setSchema(databaseName);
        final DatabaseMetaData metaData = connection.getMetaData();
        final ResultSet rs = metaData.getTables(databaseName, databaseName, name.getTableName(), TABLE_TYPE);
        if (rs.next()) {
            result = true;//from   w  ww.  ja  v  a2 s .c  o  m
        }
    } catch (final SQLException se) {
        throw this.exceptionMapper.toConnectorException(se, name);
    }
    return result;
}

From source file:com.emr.schemas.SchemerMapper.java

/**
 * Method for getting the database's tables and populating the List with the same.
 *///  ww  w .j a v a2s .co  m
public final void getDatabaseMetaData() {
    try {

        DatabaseMetaData dbmd = emrConn.getMetaData();
        String[] types = { "TABLE" };
        ResultSet rs = dbmd.getTables(null, null, "%", types);
        while (rs.next()) {
            //Add table name to Jlist
            listModel.addElement(rs.getString("TABLE_NAME"));
        }
    } catch (SQLException e) {
        String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
        JOptionPane.showMessageDialog(this,
                "Could not fetch Tables for the KenyaEMR Database. Error Details: " + stacktrace,
                "Table Names Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.talend.components.snowflake.runtime.SnowflakeSourceOrSink.java

protected List<NamedThing> getSchemaNames(RuntimeContainer container, Connection connection)
        throws IOException {
    // Returns the list with a table names (for the wh, db and schema)
    List<NamedThing> returnList = new ArrayList<>();
    SnowflakeConnectionProperties connProps = getEffectiveConnectionProperties(container);
    try {/*from  w  w w  .  ja  v  a 2  s .c om*/
        DatabaseMetaData metaData = connection.getMetaData();

        // Fetch all tables in the db and schema provided
        String[] types = { "TABLE" };
        ResultSet resultIter = metaData.getTables(getCatalog(connProps), getDbSchema(connProps), null, types);
        String tableName = null;
        while (resultIter.next()) {
            tableName = resultIter.getString("TABLE_NAME");
            returnList.add(new SimpleNamedThing(tableName, tableName));
        }
    } catch (SQLException se) {
        throw new IOException(i18nMessages.getMessage("error.searchingTable", getCatalog(connProps),
                getDbSchema(connProps), se.getMessage()), se);
    }
    return returnList;
}

From source file:ViewDB.java

 public ViewDBFrame()
{
   setTitle("ViewDB");
   setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

   tableNames = new JComboBox();
   tableNames.addActionListener(new ActionListener()
      {//  w  ww  .  ja v  a  2  s.c o m
         public void actionPerformed(ActionEvent event)
         {
            showTable((String) tableNames.getSelectedItem());
         }
      });
   add(tableNames, BorderLayout.NORTH);

   try
   {
      readDatabaseProperties();
      Connection conn = getConnection();
      try
      {
         DatabaseMetaData meta = conn.getMetaData();
         ResultSet mrs = meta.getTables(null, null, null, new String[] { "TABLE" });
         while (mrs.next())
            tableNames.addItem(mrs.getString(3));
      }
      finally
      {
         conn.close();
      }
   }
   catch (SQLException e)
   {
      JOptionPane.showMessageDialog(this, e);
   }
   catch (IOException e)
   {
      JOptionPane.showMessageDialog(this, e);
   }

   JPanel buttonPanel = new JPanel();
   add(buttonPanel, BorderLayout.SOUTH);

   previousButton = new JButton("Previous");
   previousButton.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent event)
         {
            showPreviousRow();
         }
      });
   buttonPanel.add(previousButton);

   nextButton = new JButton("Next");
   nextButton.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent event)
         {
            showNextRow();
         }
      });
   buttonPanel.add(nextButton);

   deleteButton = new JButton("Delete");
   deleteButton.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent event)
         {
            deleteRow();
         }
      });
   buttonPanel.add(deleteButton);

   saveButton = new JButton("Save");
   saveButton.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent event)
         {
            saveChanges();
         }
      });
   buttonPanel.add(saveButton);
}

From source file:org.apache.hadoop.sqoop.manager.SqlManager.java

@Override
public String[] listTables() {
    ResultSet results = null;/*from  w w  w . j  a va  2  s  . c om*/
    String[] tableTypes = { "TABLE" };
    try {
        DatabaseMetaData metaData = this.getConnection().getMetaData();
        results = metaData.getTables(null, null, null, tableTypes);
    } catch (SQLException sqlException) {
        LOG.error("Error reading database metadata: " + sqlException.toString());
        return null;
    }

    if (null == results) {
        return null;
    }

    try {
        ArrayList<String> tables = new ArrayList<String>();
        while (results.next()) {
            String tableName = results.getString("TABLE_NAME");
            tables.add(tableName);
        }

        return tables.toArray(new String[0]);
    } catch (SQLException sqlException) {
        LOG.error("Error reading from database: " + sqlException.toString());
        return null;
    }
}

From source file:eu.optimis.sm.gui.server.ServiceManagerWebServiceImpl.java

private static void writeDB(String sess_id, String name, String pass)
        throws SQLException, ClassNotFoundException {
    try {//from ww  w.j  a va2  s.co  m
        hsqlServer.start();
        Connection connection = null;
        try {
            Class.forName("org.hsqldb.jdbcDriver");
            connection = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/xdb", "sa", "");

            DatabaseMetaData md = connection.getMetaData();
            String[] types = { "TABLE", "VIEW" };
            ResultSet rs = md.getTables(null, null, null, types);

            Boolean exist = false;
            if (rs.next()) {
                logger.info("rs.getString(3) = " + rs.getString(3));
                if (rs.getString(3).equals(tableName.toUpperCase())) {
                    logger.info("Table " + rs.getString(3) + " already exists!");
                    exist = true;
                } else
                    logger.info("current table: " + rs.getString(3));
                while (rs.next()) {
                    logger.info("rs.getString(3) = " + rs.getString(3));
                    if (rs.getString(3).equals(tableName.toUpperCase())) {
                        logger.info("Table " + rs.getString(3) + " already exists!");
                        exist = true;
                    } else
                        logger.info("current table: " + rs.getString(3));
                }

            }
            if (!exist) {
                logger.info("creating table" + tableName);
                logger.info("Table " + tableName + " is created!");
                connection.prepareStatement("create table " + tableName + " (id VARCHAR(255), "
                        + "name VARCHAR(255), pass VARCHAR(255));").execute();
            }
            logger.info("insert into " + tableName + "(id, name, pass) " + "values ('" + sess_id + "', '" + name
                    + "', '" + pass + "');");

            try {
                connection.prepareStatement("insert into " + tableName + "(id, name, pass) " + "values ('"
                        + sess_id + "', '" + name + "', '" + pass + "');").execute();
                logger.info("insert: success!");

            } catch (Exception ex) {
                logger.info(ex);
            }

        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    } finally {
        if (hsqlServer != null) {
            hsqlServer.stop();
        }
    }
}

From source file:com.l2jfree.sql.L2DataSource.java

public final boolean tableExists(String tableName) {
    boolean tableExists = false;

    Connection con = null;/*from  w  w  w  . j  ava  2s.  com*/
    try {
        con = getConnection();

        DatabaseMetaData dmd = con.getMetaData();
        final ResultSet rs = dmd.getTables(_database, _schema, tableName, BASE_TABLE);
        {
            tableExists = rs.next();
        }
        rs.close();
    } catch (SQLException e) {
        _log.warn("", e);
        return false;
    } finally {
        L2Database.close(con);
    }

    return tableExists;
}

From source file:io.syndesis.filestore.impl.SqlFileStore.java

private boolean tableExists(Handle h, String tableName) {
    try {/* w w w .j  a  va  2  s. co m*/
        String tableToCheck = tableName;
        boolean caseSensitive = this.databaseKind == DatabaseKind.PostgreSQL;
        if (!caseSensitive) {
            tableToCheck = tableName.toUpperCase(Locale.ROOT);
        }
        DatabaseMetaData metaData = h.getConnection().getMetaData();

        try (ResultSet rs = metaData.getTables(null, null, tableToCheck, null)) {
            while (rs.next()) {
                String foundTable = rs.getString("TABLE_NAME");
                if (tableToCheck.equalsIgnoreCase(foundTable)) {
                    return true;
                }
            }
        }
        return false;
    } catch (SQLException ex) {
        throw FileStoreException.launderThrowable("Cannot check if the table " + tableName + " already exists",
                ex);
    }
}

From source file:yelpproject.DatabaseConnection.java

private void dropTable() throws SQLException {

    Statement stmt = null;/*w w  w .j a v  a 2s .c  o m*/

    String sqlQuery = "drop table REVIEW";

    try {
        connection = getDBConnection();

        DatabaseMetaData dbm1 = connection.getMetaData();
        ResultSet rs1 = dbm1.getTables(null, null, "REVIEW  ", null);
        if (rs1.next()) {
            stmt = connection.createStatement();
            stmt.executeUpdate(sqlQuery);
            System.out.println("Dropped!");
        } else {
            System.out.println("Table does not exist");

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }

}

From source file:it.unibas.spicy.persistence.csv.ExportCSVInstances.java

public void exportCSVInstances(MappingTask mappingTask, String directoryPath, String suffix, int scenarioNo)
        throws DAOException, SQLException, IOException {
    IDataSourceProxy dataSourceTarget = mappingTask.getTargetProxy();
    String folderPath = generateFolderPath(dataSourceTarget.getIntermediateSchema(), directoryPath, suffix, 0);
    //create CSV Folder
    new File(folderPath).mkdir();
    //connection to Postgres
    IConnectionFactory connectionFactory = new SimpleDbConnectionFactory();
    Connection connection = getConnectionToPostgres(connectionFactory);
    try {/*from w  w w  .  j  a v a2  s.  co m*/
        Statement statement = connection.createStatement();

        //get table names from target database
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] tableTypes = new String[] { "TABLE" };

        ResultSet tableResultSet = databaseMetaData.getTables(SpicyEngineConstants.MAPPING_TASK_DB_NAME,
                SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo, null, tableTypes);
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            createCSVDocument(tableName, SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo, dataSourceTarget,
                    folderPath, statement, null);
        }
    } finally {
        //close connection
        if (connection != null)
            connectionFactory.close(connection);
    }
}