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.alibaba.druid.benckmark.pool.Oracle_Case4.java

protected void printTables(DruidDataSource dataSource) throws SQLException {
    Connection conn = dataSource.getConnection();

    ResultSet rs = conn.getMetaData().getTables(null, "ALIBABA", null, new String[] { "TABLE" });
    JdbcUtils.printResultSet(rs);//from  w  w w. java 2 s  . c  o m
    rs.close();

    conn.close();
}

From source file:com.swordlord.jalapeno.DBGenerator.java

private boolean isDBAvailableAndConfigured(DataContext context, DataMap dataMap) {
    DataNode dataNode = context.getParentDataDomain().lookupDataNode(dataMap);
    boolean bResult = true;

    try {//from ww w  . j  a  va 2s.  com
        Connection connection = dataNode.getDataSource().getConnection();

        DatabaseMetaData metadata = connection.getMetaData();

        String[] types = { "TABLE" };
        ResultSet resultSet = metadata.getTables(null, null, "%", types);

        // If there is at least one, OK
        if (!resultSet.next()) {
            LOG.info("Database exists but no structure defined");
            bResult = false;
        }

        resultSet.close();
        connection.close();
    } catch (SQLException e) {
        LOG.info("SQL exception {}", e);
        bResult = false;
    }

    return bResult;
}

From source file:com.qrmedia.commons.test.dbunit.operation.MySqlKeycheckIgnoringOperation.java

@Override
public void execute(IDatabaseConnection connection, IDataSet dataSet)
        throws DatabaseUnitException, SQLException {
    Connection jdbcConnection = connection.getConnection();
    Statement statement = null;//from w  ww  .  j  a v  a2  s . co m
    String dbProductName = jdbcConnection.getMetaData().getDatabaseProductName();
    boolean dbProviderIsMySql = ((dbProductName != null) && dbProductName.contains(MYSQL_PRODUCT_NAME));
    Integer initialParameterValue = null;

    // the SQL to get and set the key checking variable's value
    final String getParameterValueSql = "select " + MYSQL_KEYCHECK_PARAMETER_NAME;
    final String setParameterValueSql = "set " + MYSQL_KEYCHECK_PARAMETER_NAME + " = ";

    // if running on MySQL, backup the existing value of the parameter and switch off key checking
    if (dbProviderIsMySql) {
        ResultSet resultSet;
        statement = jdbcConnection.createStatement();
        resultSet = statement.executeQuery(getParameterValueSql);

        // the select statment returns only one row of one column - the value of the parameter
        resultSet.next();
        initialParameterValue = Integer.valueOf(resultSet.getInt(1));

        if (LOG.isInfoEnabled()) {
            LOG.info("Disabling MySQL foreign key checking.");
        }

        // XXX: could perhaps use a prepared statement for this, as it will be called twice
        statement.execute(setParameterValueSql + "0");
    }

    // execute the actual operation
    decoratedOperation.execute(connection, dataSet);

    // restore the value of the key checking property, if running on MySQL, and clean up
    if (dbProviderIsMySql) {

        if (LOG.isInfoEnabled()) {
            LOG.info("Enabling MySQL foreign key checking.");
        }

        statement.execute(setParameterValueSql + initialParameterValue);
        statement.close();
    }

    // leave the connection open - DbUnit is responsible for handling it
}

From source file:com.googlecode.flyway.core.dbsupport.mysql.MySQLDbSupport.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(schema, null, table, null);
            return resultSet.next();
        }/*  w ww . j  a  va2 s .c  o m*/
    });
}

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

@Test
void shouldBeAbleToStartANewDatabase() throws SQLException {
    h2Database.startDatabase();/*from w  ww  . j  av  a 2  s.c  om*/

    Connection connection = h2Database.createDataSource().getConnection();
    ResultSet set = connection.getMetaData().getTables(null, null, null, null);
    assertThat(set.next(), is(true));
}

From source file:eionet.cr.test.helpers.RdfLoader.java

/**
 * Deletes all triples from the triple store.
 *
 * @throws SQLException When any sort of SQL error happens.
 *///from   w ww  .  ja  v a2s  .c  o m
public void clearAllTriples() throws SQLException {

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = SesameUtil.getSQLConnection();
        String url = conn.getMetaData().getURL();
        if (url != null && url.contains(":1111/")) {
            throw new CRRuntimeException(
                    "Triplestore clearance not supported on port 1111, as a double security measure!");
        }

        stmt = conn.createStatement();
        stmt.executeUpdate(DELETE_ALL_TRIPLES_SQL);
    } finally {
        SQLUtil.close(stmt);
        SQLUtil.close(conn);
    }
}

From source file:net.certifi.audittablegen.PostgresqlDMR.java

/**
 * Get List of ColumnDef objects for all tables
 * in the targeted database/schema.  Postgres specific code replaces 
 * 'serial' date type with integer, because the column in the audit table
 * must be of type integer and not serial.  Since this data is interpreted
 * by ChangeSourceFactory, which should be database independent, the
 * translation needs to be in the DMR./* w  ww  .j a  va 2  s  .  com*/
 * 
 * @param tableName
 * @return ArrayList of ColumnDef objects or an empty list if none are found.
 */
@Override
public List getColumns(String tableName) {

    //getDataTypes will initialize the map if it isn't already loaded
    Map<String, DataTypeDef> dtds = getDataTypes();

    List columns = new ArrayList<>();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getColumns(null, verifiedSchema, tableName, null);

        //load all of the metadata in the result set into a map for each column

        ResultSetMetaData rsmd = rs.getMetaData();
        int metaDataColumnCount = rsmd.getColumnCount();
        if (!rs.isBeforeFirst()) {
            throw new RuntimeException(
                    "No results for DatabaseMetaData.getColumns(" + verifiedSchema + "." + tableName + ")");
        }
        while (rs.next()) {
            ColumnDef columnDef = new ColumnDef();
            Map columnMetaData = new CaseInsensitiveMap();
            for (int i = 1; i <= metaDataColumnCount; i++) {
                columnMetaData.put(rsmd.getColumnName(i), rs.getString(i));
            }
            columnDef.setName(rs.getString("COLUMN_NAME"));

            String type_name = rs.getString("TYPE_NAME");
            if (type_name.equalsIgnoreCase("serial")) {
                columnDef.setTypeName("int4");
            } else {
                columnDef.setTypeName(type_name);
            }
            columnDef.setSqlType(rs.getInt("DATA_TYPE"));
            columnDef.setSize(rs.getInt("COLUMN_SIZE"));
            columnDef.setDecimalSize(rs.getInt("DECIMAL_DIGITS"));
            columnDef.setSourceMeta(columnMetaData);

            if (dtds.containsKey(columnDef.getTypeName())) {
                columnDef.setDataTypeDef(dtds.get(columnDef.getTypeName()));
            } else {
                throw new RuntimeException(
                        "Missing DATA_TYPE definition for data type " + columnDef.getTypeName());
            }
            columns.add(columnDef);
        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    return columns;

}

From source file:com.googlecode.flyway.core.dbsupport.sqlserver.SQLServerDbSupport.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, table, null);
            return resultSet.next();
        }/*ww  w  .j  a  v  a2  s. co m*/
    });
}

From source file:de.erdesignerng.dialect.oracle.OracleReverseEngineeringStrategy.java

@Override
public List<SchemaEntry> getSchemaEntries(Connection aConnection) throws SQLException {

    List<SchemaEntry> theList = new ArrayList<>();

    DatabaseMetaData theMetadata = aConnection.getMetaData();
    ResultSet theResult = theMetadata.getSchemas();

    while (theResult.next()) {
        String theSchemaName = theResult.getString("TABLE_SCHEM");
        String theCatalogName = null;

        theList.add(new SchemaEntry(theCatalogName, theSchemaName));
    }/*  w  w w . j  a va2 s . c  o m*/

    return theList;
}

From source file:io.pivotal.security.controller.v1.health.DataSourceHealthIndicator.java

private String getProduct() {
    return this.jdbcTemplate.execute(new ConnectionCallback<String>() {
        @Override//from  www . j av  a2 s.  co m
        public String doInConnection(Connection connection) throws SQLException, DataAccessException {
            return connection.getMetaData().getDatabaseProductName();
        }
    });
}