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.pinterest.pinlater.backends.mysql.MySQLBackendUtils.java

/**
 * Gets the names of all queues found at the specified MySQL instance. Note that it is the
 * callers responsibility to close the connection after this method is called.
 *
 * @param conn Connection to the MySQL instance.
 * @param shardName/*  w w  w. j  av a2s  .  c o m*/
 * @return Set containing queue name strings.
 */
public static Set<String> getQueueNames(Connection conn, String shardName) throws SQLException {
    ResultSet dbNameRs = conn.getMetaData().getCatalogs();
    Set<String> queueNames = Sets.newHashSet();
    while (dbNameRs.next()) {
        String name = dbNameRs.getString("TABLE_CAT");
        if (name.startsWith(MySQLBackendUtils.PINLATER_QUEUE_DB_PREFIX)
                && shardNameFromDBName(name).equals(shardName)) {
            queueNames.add(MySQLBackendUtils.queueNameFromDBName(name));
        }
    }
    return queueNames;
}

From source file:com.jagornet.dhcp.db.DbSchemaManager.java

/**
 * Validate schema.//from  w w  w.  j av  a2 s.c o m
 * 
 * @param dataSource the data source
 * 
 * @throws SQLException if there is a problem with the database
 * @throws IOExcpetion if there is a problem reading the schema file
 * 
 * returns true if database was created, false otherwise
 */
public static boolean validateSchema(DataSource dataSource, String schemaFilename, int schemaVersion)
        throws SQLException, IOException {
    boolean schemaCreated = false;

    List<String> tableNames = new ArrayList<String>();

    Connection conn = dataSource.getConnection();
    DatabaseMetaData dbMetaData = conn.getMetaData();

    log.info("JDBC Connection Info:\n" + "url = " + dbMetaData.getURL() + "\n" + "database = "
            + dbMetaData.getDatabaseProductName() + " " + dbMetaData.getDatabaseProductVersion() + "\n"
            + "driver = " + dbMetaData.getDriverName() + " " + dbMetaData.getDriverVersion());

    String[] types = { "TABLE" };
    ResultSet rs = dbMetaData.getTables(null, null, "%", types);
    if (rs.next()) {
        tableNames.add(rs.getString("TABLE_NAME"));
    } else {
        createSchema(dataSource, schemaFilename);
        dbMetaData = conn.getMetaData();
        rs = dbMetaData.getTables(null, null, "%", types);
        schemaCreated = true;
    }
    while (rs.next()) {
        tableNames.add(rs.getString("TABLE_NAME"));
    }

    String[] schemaTableNames;
    if (schemaVersion <= 1) {
        schemaTableNames = TABLE_NAMES;
    } else {
        schemaTableNames = TABLE_NAMES_V2;
    }

    if (tableNames.size() == schemaTableNames.length) {
        for (int i = 0; i < schemaTableNames.length; i++) {
            if (!tableNames.contains(schemaTableNames[i])) {
                throw new IllegalStateException("Invalid database schema: unknown tables");
            }
        }
    } else {
        throw new IllegalStateException("Invalid database schema: wrong number of tables");
    }

    return schemaCreated;
}

From source file:mangotiger.sql.SQL.java

private static String asString(final Connection connection) throws SQLException {
    final DatabaseMetaData metaData = connection.getMetaData();
    return metaData.getURL() + ":username=" + metaData.getUserName();
}

From source file:Student.java

public static void checkData() throws Exception {
        Class.forName("org.hsqldb.jdbcDriver");
        Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial", "sa", "");
        Statement st = conn.createStatement();

        ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
        while (mrs.next()) {
            String tableName = mrs.getString(3);
            System.out.println("\n\n\n\nTable Name: " + tableName);

            ResultSet rs = st.executeQuery("select * from " + tableName);
            ResultSetMetaData metadata = rs.getMetaData();
            while (rs.next()) {
                System.out.println(" Row:");
                for (int i = 0; i < metadata.getColumnCount(); i++) {
                    System.out.println("    Column Name: " + metadata.getColumnLabel(i + 1) + ",  ");
                    System.out.println("    Column Type: " + metadata.getColumnTypeName(i + 1) + ":  ");
                    Object value = rs.getObject(i + 1);
                    System.out.println("    Column Value: " + value + "\n");
                }/*from  w w w .  j  a  va 2  s  . co  m*/
            }
        }
    }

From source file:ips1ap101.lib.core.db.util.InterpreteSqlCachingServiceLocator.java

private static synchronized InterpreteSql getInstance(Connection connection) {
    Bitacora.trace(InterpreteSqlCachingServiceLocator.class, "getInstance", connection);
    if (connection == null) {
        return null;
    } else {/*from www .ja  v  a 2s.co  m*/
        try {
            String driver = connection.getMetaData().getDriverName();
            String url = connection.getMetaData().getURL();
            //              String user = connection.getMetaData().getUserName();
            //              String password = connection.getMetaData().getUserName();
            String version = connection.getMetaData().getDriverVersion();
            return getInstance(driver, url, version);
        } catch (SQLException ex) {
            Bitacora.logFatal(ex);
        }
        return null;
    }
}

From source file:com.egt.core.db.util.InterpreteSqlCachingServiceLocator.java

private static synchronized InterpreteSql getInstance(Connection connection) {
    Bitacora.trace(InterpreteSqlCachingServiceLocator.class, "getInstance", connection);
    if (connection == null) {
        return null;
    } else {/*from w  ww . j  a  v a 2 s. c  o m*/
        try {
            String driver = connection.getMetaData().getDriverName();
            String url = connection.getMetaData().getURL();
            //              String user = connection.getMetaData().getUserName();
            //              String password = connection.getMetaData().getUserName();
            String version = connection.getMetaData().getDriverVersion();
            return getInstance(driver, url, version);
        } catch (SQLException ex) {
            TLC.getBitacora().fatal(ex);
        }
        return null;
    }
}

From source file:de.griffel.confluence.plugins.plantuml.DatasourceHelper.java

/**
 * Returns Database meta data.//from   ww w .j  a  v  a2s .co  m
 *
 * @param datasource data source
 * @param attributes attributes to get
 * @return Map with requested attributes
 */
public static Map<String, String> getDatabaseMetadata(DataSource datasource, List<String> attributes) {
    final Map<String, String> databaseMetadata = new HashMap<String, String>();
    Connection con = null;
    try {
        con = datasource.getConnection();
        final DatabaseMetaData dbmd = con.getMetaData();
        for (String attribute : attributes) {
            if (CATALOGS.equals(attribute)) {
                databaseMetadata.put(CATALOGS, StringUtils.join(getCatalogs(dbmd), ","));
            } else if (TABLE_TYPES.equals(attribute)) {
                databaseMetadata.put(TABLE_TYPES, StringUtils.join(getTableTypes(dbmd), ","));
            } else {
                fillValue(dbmd, attribute, databaseMetadata);
            }
        }
    } catch (SQLException e) {
        log.debug("SQLException accessing metadata", e);
        databaseMetadata.put(ERROR, e.getMessage());
    } finally {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException ex) {
            log.debug("SQLException closing connection", ex);
        }
    }
    return databaseMetadata;
}

From source file:com.aionemu.commons.database.DatabaseFactory.java

public synchronized static void init(String configFilePath) {
    if (dataSource != null) {
        return;/*from  w ww . j  a v a 2 s .  c  o  m*/
    }

    if (!configFilePath.equals("")) {
        try {
            Properties dbProps = PropertiesUtils.load(configFilePath);
            ConfigurableProcessor.process(DatabaseConfig.class, dbProps);
        } catch (IOException ex) {
            log.fatal("Cannot load database config", ex);
        }
    }

    try {
        DatabaseConfig.DATABASE_DRIVER.newInstance();
    } catch (Exception e) {
        log.fatal("Error obtaining DB driver", e);
        throw new Error("DB Driver doesnt exist!");
    }

    connectionPool = new GenericObjectPool();

    if (DatabaseConfig.DATABASE_CONNECTIONS_MIN > DatabaseConfig.DATABASE_CONNECTIONS_MAX) {
        log.error("Please check your database configuration. Minimum amount of connections is > maximum");
        DatabaseConfig.DATABASE_CONNECTIONS_MAX = DatabaseConfig.DATABASE_CONNECTIONS_MIN;
    }

    connectionPool.setMaxIdle(DatabaseConfig.DATABASE_CONNECTIONS_MIN);
    connectionPool.setMaxActive(DatabaseConfig.DATABASE_CONNECTIONS_MAX);
    /* test if connection is still valid before returning */
    //connectionPool.setTestOnBorrow(true);

    try {
        dataSource = setupDataSource();
        Connection c = getConnection();
        DatabaseMetaData dmd = c.getMetaData();
        databaseName = dmd.getDatabaseProductName();
        databaseMajorVersion = dmd.getDatabaseMajorVersion();
        databaseMinorVersion = dmd.getDatabaseMinorVersion();
        c.close();
    } catch (Exception e) {
        log.fatal("Error with connection string: " + DatabaseConfig.DATABASE_URL, e);
        throw new Error("DatabaseFactory not initialized!");
    }

    log.info("Successfully connected to database");
}

From source file:cn.org.citycloud.srdz.utils.Hibernates.java

private static String getJdbcUrlFromDataSource(DataSource dataSource) {
    Connection connection = null;
    try {//from  w w  w. j  a v  a  2 s.c om
        connection = dataSource.getConnection();
        if (connection == null) {
            throw new IllegalStateException("Connection returned by DataSource [" + dataSource + "] was null");
        }
        return connection.getMetaData().getURL();
    } catch (SQLException e) {
        throw new RuntimeException("Could not get database url", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:edu.mayo.cts2.uriresolver.dao.DAOUtiltities.java

public static boolean checkTablesExist(DataSource ds) {
    Connection con = null;
    boolean tablesExist = true;
    try {/*  w  ww .j  av  a  2  s . c  o  m*/
        con = ds.getConnection();
        DatabaseMetaData metaData = con.getMetaData();
        for (int i = 0; i < TABLENAMES.length; i++) {
            if (!tableExists(metaData, TABLENAMES[i])) {
                tablesExist = false;
                logger.error("Database is missing table: " + TABLENAMES[i]);
            }
        }
        con.close();
    } catch (SQLException e) {
        logger.error("Unknown error while checking tables exist, check all connection values");
        return false;
    } finally {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            logger.error("Error while closing data source connection object: " + e.getMessage());
            return false;
        }
    }

    return tablesExist;
}