Example usage for java.sql Connection getMetaData

List of usage examples for java.sql Connection getMetaData

Introduction

In this page you can find the example usage for java.sql Connection getMetaData.

Prototype

DatabaseMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.

Usage

From source file:com.quartzdesk.executor.dao.AbstractDao.java

/**
 * Checks if the specified table exists in the specified schema and returns true if
 * it exists, false otherwise. This method tries to look up the table using both
 * lower-case and upper-case schema and table names because some databases seems to
 * require the names to be in upper case (DB2, Oracle), whereas other databases require
 * the names to be in lower-case./* ww  w .java2s  . c o m*/
 *
 * @param session    a Hibernate session.
 * @param schemaName an optional schema name where to look for the table name.
 * @param tableName  a table name.
 * @return true if the table exists, false otherwise.
 */
public boolean tableExists(Session session, final String schemaName, final String tableName) {
    final AtomicBoolean tableExists = new AtomicBoolean(false);

    session.doWork(new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            log.debug("Checking if table '{}' exists.", tableName);

            DatabaseMetaData metaData = connection.getMetaData();

            // 1. attempt - try schema and table name in lower-case (does not work in DB2 and Oracle)
            ResultSet res = metaData.getTables(null,
                    schemaName == null ? null : schemaName.toLowerCase(Locale.US),
                    tableName.toLowerCase(Locale.US), new String[] { "TABLE" });

            tableExists.set(res.next());
            DbUtils.close(res);

            if (tableExists.get()) {
                log.debug("Table '{}' exists.", tableName);
            } else {
                // 2. attempt - try schema and table name in upper-case (required for DB2 and Oracle)
                res = metaData.getTables(null, schemaName == null ? null : schemaName.toUpperCase(Locale.US),
                        tableName.toUpperCase(Locale.US), new String[] { "TABLE" });

                tableExists.set(res.next());
                DbUtils.close(res);

                if (tableExists.get()) {
                    log.debug("Table '{}' exists.", tableName);
                } else {
                    log.debug("Table '{}' does not exist.", tableName);
                }
            }
        }
    });

    return tableExists.get();
}

From source file:com.github.p4535992.database.datasource.database.data.Dao.java

public Set<String> getPrimaryKeys() {
    if (primaryKeys != null) {
        return primaryKeys;
    }// ww  w  . j a  va  2s  .  c  o  m

    primaryKeys = new HashSet<>();
    database.getJdbcTemplate().execute(new ConnectionCallback<Void>() {
        @Override
        public Void doInConnection(Connection con) throws SQLException, DataAccessException {
            DatabaseMetaData metadata = con.getMetaData();
            //if the table name is in lower case it won't work (at least not with HSQLDB)
            try (ResultSet rs = metadata.getPrimaryKeys(null, null, tableName.toUpperCase())) {
                while (rs.next()) {
                    primaryKeys.add(rs.getString("COLUMN_NAME"));
                }
            }
            return null;
        }

    });

    return primaryKeys;
}

From source file:name.marcelomorales.siqisiqi.bonecp.DataSourceProviderTest.java

@Test
public void testOneDatabase() throws Exception {
    Config config = ConfigFactory.load();

    DataSourceProvider dsp = new DataSourceProvider(config);

    dsp.getBoneCPConfig().setAcquireRetryDelayInMs(2000);

    DataSource dataSource = dsp.get();

    Connection connection = dataSource.getConnection();

    DatabaseMetaData metaData = connection.getMetaData();

    assertEquals("Apache Derby", metaData.getDatabaseProductName());

    connection.close();/* w  w w .  ja va 2 s  .  c o  m*/

    dsp.close();
}

From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.jicai.db.impl.AbstractJiCaiDBExtractService.java

public final SystemVO getSysInfos(String schema, int start, int limit, boolean flag) throws Exception {
    Connection conn = null;
    try {//ww  w .  j  a v  a  2 s.  c om
        conn = jdbcTemplate.getDataSource().getConnection();
        metaData = conn.getMetaData();
        log.info("???!");
        return internalGetSchemas(schema, start, limit, flag);
    } catch (Exception e) {
        log.error("DB??SQL!DB????!", e);
        AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR,
                "DB??SQL!DB????!");
        if (conn != null) {
            conn.close();
        }
        throw e;
    } finally {
        // ??,???
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:com.netflix.metacat.connector.snowflake.SnowflakeConnectorTableService.java

@Override
protected ResultSet getColumns(@Nonnull @NonNull final Connection connection,
        @Nonnull @NonNull final QualifiedName name) throws SQLException {
    return connection.getMetaData().getColumns(connection.getCatalog(), name.getDatabaseName(),
            name.getTableName(), JdbcConnectorUtils.MULTI_CHARACTER_SEARCH);
}

From source file:name.marcelomorales.siqisiqi.bonecp.DataSourceProviderTest.java

@Test
public void testWithDependencyInjector() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override/*  ww  w .  j  a  va 2  s.  c  o m*/
        protected void configure() {
            bind(Config.class).toInstance(ConfigFactory.load());
            bind(DataSourceProvider.class).in(Scopes.SINGLETON);
            bind(DataSource.class).toProvider(DataSourceProvider.class).in(Scopes.SINGLETON);
        }
    });

    DataSource dataSource = injector.getInstance(DataSource.class);

    Connection connection = dataSource.getConnection();

    DatabaseMetaData metaData = connection.getMetaData();

    assertEquals("Apache Derby", metaData.getDatabaseProductName());

    connection.close();

    injector.getInstance(DataSourceProvider.class).close();
}

From source file:com.googlecode.flyway.core.dbsupport.postgresql.PostgreSQLDbSupport.java

public boolean tableExists(final String schema, final String table) {
    return (Boolean) jdbcTemplate.execute(new ConnectionCallback() {
        public Boolean doInConnection(Connection connection) throws SQLException, DataAccessException {
            ResultSet resultSet = connection.getMetaData().getTables(null, schema.toLowerCase(),
                    table.toLowerCase(), new String[] { "TABLE" });
            return resultSet.next();
        }// w ww. ja v  a2s.  c  om
    });
}

From source file:database.HashTablesTools.java

public static void createTablesIfTheyDontExists(Connection connection, String tableSequenceName,
        String tableFailureName) {

    ResultSet resultTables = null;
    try {//  w w  w . j  a  v a 2s .c  om

        /**
         DatabaseMetaData dmd = connection.getMetaData();
         ResultSet rs = dmd.getSchemas();
         List<String> schemas = new ArrayList<String>();
         while (rs.next()) {
         schemas.add(rs.getString("TABLE_SCHEM"));
         }
         rs.close();
         System.out.println("Schemas : ");
         for (String schema : schemas) {
         System.out.println(schema);
         }
         */
        // get database metadata
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet rsSchema = metaData.getTables(null, "ME", "%", null);
        List<String> tables = new ArrayList<String>();
        while (rsSchema.next()) {
            tables.add(rsSchema.getString(3)); // 3: table name
        }
        rsSchema.close();

        if (!tables.contains(tableSequenceName.toUpperCase())) {
            System.out.println(tableSequenceName + " dont exist");
            createTables(connection, tableSequenceName, tableFailureName);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

From source file:com.univocity.app.data.Dao.java

public Set<String> getPrimaryKeys() {
    if (primaryKeys != null) {
        return primaryKeys;
    }/*from  w w w .java2 s  . c  om*/

    primaryKeys = new HashSet<String>();
    database.getJdbcTemplate().execute(new ConnectionCallback<Void>() {
        @Override
        public Void doInConnection(Connection con) throws SQLException, DataAccessException {
            DatabaseMetaData metadata = con.getMetaData();
            //if the table name is in lower case it won't work (at least not with HSQLDB)
            ResultSet rs = metadata.getPrimaryKeys(null, null, tableName.toUpperCase());
            try {
                while (rs.next()) {
                    primaryKeys.add(rs.getString("COLUMN_NAME"));
                }
            } finally {
                rs.close();
            }
            return null;
        }

    });

    return primaryKeys;
}

From source file:com.thoughtworks.go.server.database.H2Database.java

public void startDatabase() {
    if (systemEnvironment.inDbDebugMode()) {
        if (tcpServer != null) {
            return;
        }//from  w ww.  jav a 2  s  . co m
        try {
            DataSource ds = createDataSource();
            Connection con = ds.getConnection();
            ResultSet set = con.getMetaData().getTables(null, null, null, null);
            set.next();
            set.close();
            con.close();
            LOG.info("Database is already running.");
            return;
        } catch (Exception e) {
            LOG.info("Database is not running - starting a new one.");
        }
        try {
            LOG.info("Starting h2 server in debug mode : " + "port=" + configuration.getPort() + " baseDir="
                    + systemEnvironment.getDbPath().getCanonicalPath());
            String[] args = { "-tcp", "-tcpAllowOthers", "-tcpPort", String.valueOf(configuration.getPort()),
                    "-baseDir", systemEnvironment.getDbPath().getCanonicalPath() };
            tcpServer = Server.createTcpServer(args);
            tcpServer.start();
        } catch (Exception e) {
            bomb("Could not create database server.", e);
        }
    }
}