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.jaspersoft.jasperserver.remote.dbservices.impl.MetaDataServiceImpl.java

/**
 * This method invokes a method ( a total of around 170 odd ) on the DatabaseMetaData object based on 
 * method name and parameters. If the result is a Resultset a CachedRowSet object is populated with 
 * its results and returned. Else all other types are returned as is.
 * @param request//w w w .  j  a v a  2 s.  c om
 * @return
 */

public byte[] getDBMetaData(Resource resource, CachedRowSetWrapper crw) {
    long startTime = System.currentTimeMillis();
    byte[] ret = new byte[0];
    Connection conn = null;
    Method method = null;
    CachedRowSet crs = null;
    Object result = null;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Enter getDBMetaData .. Start Time" + System.currentTimeMillis());
        }
        if (crw.getParameters() != null) {
            for (int i = 0; i < crw.getParameters().length; i++) {
                Object param = crw.getParameters()[i];

                //if(param instanceof String && ((String) param).length() == 0){
                if (param instanceof String && StringUtil.isEmpty((String) param)) {
                    crw.getParameters()[i] = null; // make it null
                }
            }
        }
        conn = QueryUtil.getConnection(resource);
        DatabaseMetaData dm = conn.getMetaData();
        method = QueryUtil.findMethod(dm, crw.getRequestId(), crw.getParameters());
        if (null != method) {
            result = method.invoke(dm, crw.getParameters());
            if (null != result) {
                if (result instanceof java.sql.ResultSet) { // got a resultset
                    crs = RowSetProvider.newFactory().createCachedRowSet();
                    crs.populate((ResultSet) result);
                    ((java.sql.ResultSet) result).close(); // close the resultset
                    result = crs;
                }
                if (result instanceof Serializable) {
                    ret = JasperSerializationUtil.serialize((Serializable) result);
                } else {
                    logger.warn("Cannot serialize object" + result.getClass().getName());
                }
            } // if
        } else {
            throw new RemoteException(crw.getRequestId() + " method name is not supported.");
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new RemoteException("Meta Data fail." + ex.getMessage());
    } finally {
        try {
            if (conn != null)
                conn.close();
            if (crs != null)
                crs.close();
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new RemoteException("Meta Data fail." + ex.getMessage());
        }
        if (logger.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Exit getDBMetaData .. Total Time Spent: " + elapsedTime);
        }
    }
    return ret;
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

/**
 * Wrapper for {@link java.sql.DatabaseMetaData#getTables(String, String, String, String[])}
 *
 * @param connection open JDBC connection
 * @param schema schema name, can be null
 * @param tableName table name or pattern, optionally fully qualified in the form schema.tableName
 * @return ResultSet containing the table and view metadata
 *
 * @throws SQLException//from  w w w .j  a v a 2 s .c om
 */
public ResultSet getTableAndViewMetadata(Connection connection, String schema, String tableName)
        throws SQLException {
    return connection.getMetaData().getTables(connection.getCatalog(), schema, tableName,
            METADATA_TABLE_VIEW_TYPE);
}

From source file:com.ah.be.communication.BusinessUtil.java

private static String[] getDBSettings() throws SQLException {
    String[] dbSettings = new String[5];
    Connection con = null;

    try {//from  w  w  w . j  a  v  a2  s  .  c  o m
        con = QueryUtil.getConnection();
        DatabaseMetaData mData = con.getMetaData();
        String[] urls = DBOperationUtil.parseJDBCUrl(mData.getURL());
        if (urls != null && urls.length == 3) {
            dbSettings[0] = urls[0];
            dbSettings[1] = urls[1];
            dbSettings[2] = urls[2];
            dbSettings[3] = System.getProperty("hm.connection.username");
            dbSettings[4] = System.getProperty("hm.connection.password");
        }
        return dbSettings;
    } finally {
        if (con != null && !con.isClosed()) {
            try {
                con.close();
            } catch (SQLException e) {
                log.error("Connection close error.", e);
            }
        }
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

/**
 * Wrapper for {@link java.sql.DatabaseMetaData#getColumns(String, String, String, String)} that detects
 * the format of the supplied tableName.
 *
 * @param connection An open JDBC connection
 * @param tableName table name that is optionally fully qualified with a schema in the form schema.tableName
 * @return ResultSet containing the column metadata
 *
 * @throws SQLException/* w ww  . j  av a 2s. c o m*/
 */
public ResultSet getColumnMetadata(Connection connection, String schema, String tableName) throws SQLException {
    DatabaseMetaData metadata = connection.getMetaData();
    return metadata.getColumns(connection.getCatalog(), schema, tableName, null); // Get all columns for this table
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

/**
 * Wrapper for {@link java.sql.DatabaseMetaData#getTables(String, String, String, String[])}
 *
 * @param connection open JDBC connection
 * @param schema schema name, can be null
 * @param tableName table name or pattern, optionally fully qualified in the form schema.tableName
 * @return ResultSet containing the table metadata
 *
 * @throws SQLException//from  w  w w.  j  a  v a 2  s . c om
 */
public ResultSet getTableMetadata(Connection connection, String schema, String tableName) throws SQLException {
    DatabaseMetaData metadata = connection.getMetaData();
    return metadata.getTables(connection.getCatalog(), schema, tableName, METADATA_TABLE_TYPE);
}

From source file:jmdbtools.JMdbTools.java

private void createTables(DbSchema schema, Connection conn) throws SQLException {

    Statement stmt = conn.createStatement();
    for (DbTable dbTable : schema.getTables()) {
        String createTableSql = new CreateTableQuery(dbTable, true).validate().toString();

        //TODO: DANGEROUS: auto override tables. Add explicit option to enable
        if (dbOverwrite) {
            log("Dropping existing table", "warn");
            stmt.executeUpdate("DROP TABLE IF EXISTS `" + dbTable.getName() + "`");
            log("creating table:" + dbTable.getName(), "info");
            stmt.executeUpdate(createTableSql);
        } else {/*  w  w  w.j a  va2s.  c  om*/
            DatabaseMetaData meta = conn.getMetaData();
            ResultSet res = meta.getTables(null, null, dbTable.getName(), new String[] { "TABLE" });
            if (res.last()) {
                //there are entries for "TABLE" with this name don't try to create table
                log("Table already exists:" + dbTable.getName(), "info");

            } else {
                log("creating table:" + dbTable.getName(), "info");
                stmt.executeUpdate(createTableSql);
            }
        }
    }
}

From source file:org.zht.framework.zhtdao.hibernate.impl.HibernateBaseDaoImpl.java

@Override
public String getDatabaseInfo() {
    final StringBuilder buf = new StringBuilder("");
    this.getCurrentSession().doWork(new Work() {
        public void execute(Connection conn) throws SQLException {
            try {
                buf.append(conn.getMetaData().getDatabaseProductName()).append(" ");
                buf.append(conn.getMetaData().getDatabaseProductVersion()).append(" ");
                buf.append(conn.getMetaData().getDatabaseMajorVersion()).append(" ");
            } catch (SQLException e) {
                e.printStackTrace();//from  w  w w .j  a v a 2s  .com
            }
        }
    });
    return buf.toString();
}

From source file:org.apache.syncope.core.util.ImportExport.java

private void doExportTable(final TransformerHandler handler, final Connection conn, final String tableName)
        throws SQLException, SAXException {

    AttributesImpl attrs = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;/*from  ww  w . j a v  a 2  s.  c  o m*/
    ResultSet pkeyRS = null;

    try {
        // ------------------------------------
        // retrieve primary keys to perform an ordered select

        final DatabaseMetaData meta = conn.getMetaData();
        pkeyRS = meta.getPrimaryKeys(null, null, tableName);

        final StringBuilder orderBy = new StringBuilder();

        while (pkeyRS.next()) {
            final String columnName = pkeyRS.getString("COLUMN_NAME");

            if (columnName != null) {
                if (orderBy.length() > 0) {
                    orderBy.append(",");
                }

                orderBy.append(columnName);
            }
        }

        // ------------------------------------
        stmt = conn.prepareStatement(
                "SELECT * FROM " + tableName + " a" + (orderBy.length() > 0 ? " ORDER BY " + orderBy : ""));

        rs = stmt.executeQuery();
        for (int rowNo = 0; rs.next(); rowNo++) {
            attrs.clear();

            final ResultSetMetaData rsMeta = rs.getMetaData();

            for (int i = 0; i < rsMeta.getColumnCount(); i++) {
                final String columnName = rsMeta.getColumnName(i + 1);
                final Integer columnType = rsMeta.getColumnType(i + 1);

                // Retrieve value taking care of binary values.
                String value = getValues(rs, columnName, columnType);

                if (value != null) {
                    attrs.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, attrs);
            handler.endElement("", "", tableName);
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (pkeyRS != null) {
            try {
                pkeyRS.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

/**
 * Wrapper for {@link java.sql.DatabaseMetaData#getImportedKeys(String, String, String)}
 *
 * @param connection An open JDBC connection
 * @param tableName table name that is optionally fully qualified with a schema in the form schema.tableName
 * @return List of Table Names whose primary key are referred as foreign key by the table tableName
 *
 * @throws SQLException/*from www . j  ava 2  s .c o  m*/
 */
public Set<String> getReferredTables(Connection connection, String schema, String tableName)
        throws SQLException {
    DatabaseMetaData metadata = connection.getMetaData();

    ResultSet result = metadata.getImportedKeys(connection.getCatalog(), schema, tableName);
    Set<String> referredTables = new HashSet<>();
    while (result.next()) {
        referredTables.add(result.getString(PK_TABLE_NAME));
    }
    return referredTables;
}