List of usage examples for java.sql Connection getMetaData
DatabaseMetaData getMetaData() throws SQLException;
DatabaseMetaData
object that contains metadata about the database to which this Connection
object represents a connection. From source file:jef.database.DbUtils.java
/** * ???//from ww w . j a va 2 s . c o m * * @param conn * @return * @throws SQLException */ public static ConnectInfo tryAnalyzeInfo(Connection conn) throws SQLException { DatabaseMetaData meta = conn.getMetaData(); ConnectInfo info = new ConnectInfo(); info.user = meta.getUserName(); info.url = meta.getURL(); info.parse();// ?profile, ????? return info; }
From source file:com.netflix.metacat.connector.jdbc.services.JdbcConnectorTableService.java
/** * Get the tables. See {@link java.sql.DatabaseMetaData#getTables(String, String, String, String[]) getTables} for * expected format of the ResultSet columns. * * @param connection The database connection to use * @param name The qualified name of the database to get tables for * @param prefix An optional database table name prefix to search for * @return The result set with columns as described in the getTables method from java.sql.DatabaseMetaData * @throws SQLException on query error//w w w. j av a 2 s. c o m */ protected ResultSet getTables(@Nonnull @NonNull final Connection connection, @Nonnull @NonNull final QualifiedName name, @Nullable final QualifiedName prefix) throws SQLException { final String database = name.getDatabaseName(); final DatabaseMetaData metaData = connection.getMetaData(); return prefix == null || StringUtils.isEmpty(prefix.getTableName()) ? metaData.getTables(database, database, null, TABLE_TYPES) : metaData.getTables(database, database, prefix.getTableName() + JdbcConnectorUtils.MULTI_CHARACTER_SEARCH, TABLE_TYPES); }
From source file:de.hybris.platform.virtualjdbc.jalo.AbstractVjdbcSqlTest.java
protected void updateTest(final Connection vjdbcConn) throws Exception { PreparedStatement stmt = null; try {/*from ww w . j av a2 s.co m*/ final String tablePrefix = Registry.getCurrentTenant().equals(Registry.getMasterTenant()) ? "" : Registry.getCurrentTenant().getTenantID() + "_"; final String realQuery = String.format(UPDATE_PRODUCTS, StringUtils.isEmpty(tablePrefix) ? "" : tablePrefix); stmt = vjdbcConn.prepareStatement(realQuery); LOG.info("Underlying data base url:: " + vjdbcConn.getMetaData().getURL()); LOG.info("Executing query:: " + UPDATE_PRODUCTS); stmt.executeUpdate(); } finally { Utilities.tryToCloseJDBC(vjdbcConn, stmt, null); } }
From source file:net.gcolin.simplerepo.search.SearchController.java
public SearchController(ConfigurationManager configManager) throws IOException { this.configManager = configManager; File plugins = new File(configManager.getRoot(), "plugins"); plugins.mkdirs();// ww w.j av a 2 s . c o m System.setProperty("derby.system.home", plugins.getAbsolutePath()); BasicDataSource s = new BasicDataSource(); s.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); s.setUrl("jdbc:derby:search" + (new File(plugins, "search").exists() ? "" : ";create=true")); s.setUsername("su"); s.setPassword(""); s.setMaxTotal(10); s.setMinIdle(0); s.setDefaultAutoCommit(true); datasource = s; Set<String> allTables = new HashSet<>(); Connection connection = null; try { try { connection = datasource.getConnection(); connection.setAutoCommit(false); DatabaseMetaData dbmeta = connection.getMetaData(); try (ResultSet rs = dbmeta.getTables(null, null, null, new String[] { "TABLE" })) { while (rs.next()) { allTables.add(rs.getString("TABLE_NAME").toLowerCase()); } } if (!allTables.contains("artifact")) { QueryRunner run = new QueryRunner(); run.update(connection, "CREATE TABLE artifactindex(artifact bigint NOT NULL, version bigint NOT NULL)"); run.update(connection, "INSERT INTO artifactindex (artifact,version) VALUES (?,?)", 1L, 1L); run.update(connection, "CREATE TABLE artifact(id bigint NOT NULL,groupId character varying(120), artifactId character varying(120),CONSTRAINT artifact_pkey PRIMARY KEY (id))"); run.update(connection, "CREATE TABLE artifactversion(artifact_id bigint NOT NULL,id bigint NOT NULL," + "version character varying(100)," + "reponame character varying(30)," + "CONSTRAINT artifactversion_pkey PRIMARY KEY (id)," + "CONSTRAINT fk_artifactversion_artifact_id FOREIGN KEY (artifact_id) REFERENCES artifact (id) )"); run.update(connection, "CREATE TABLE artifacttype(version_id bigint NOT NULL,packaging character varying(20) NOT NULL,classifier character varying(30)," + "CONSTRAINT artifacttype_pkey PRIMARY KEY (version_id,packaging,classifier)," + "CONSTRAINT fk_artifacttype_version FOREIGN KEY (version_id) REFERENCES artifactversion (id))"); run.update(connection, "CREATE INDEX artifactindex ON artifact(groupId,artifactId)"); run.update(connection, "CREATE INDEX artifactgroupindex ON artifact(groupId)"); run.update(connection, "CREATE INDEX artifactversionindex ON artifactversion(version)"); } connection.commit(); } catch (SQLException ex) { connection.rollback(); throw ex; } finally { DbUtils.close(connection); } } catch (SQLException ex) { throw new IOException(ex); } }
From source file:com.haulmont.cuba.core.sys.dbupdate.DbUpdaterEngine.java
public boolean dbInitialized() throws DbInitializationException { log.trace("Checking if the database is initialized"); Connection connection = null; try {/*from w w w .jav a 2 s .c om*/ connection = getDataSource().getConnection(); DatabaseMetaData dbMetaData = connection.getMetaData(); DbProperties dbProperties = new DbProperties(getConnectionUrl(connection)); boolean isSchemaByUser = DbmsSpecificFactory.getDbmsFeatures().isSchemaByUser(); String schemaName = isSchemaByUser ? dbMetaData.getUserName() : dbProperties.getCurrentSchemaProperty(); ResultSet tables = dbMetaData.getTables(null, schemaName, null, null); boolean found = false; while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); if ("SYS_DB_CHANGELOG".equalsIgnoreCase(tableName)) { log.trace("Found SYS_DB_CHANGELOG table"); changelogTableExists = true; } if ("SEC_USER".equalsIgnoreCase(tableName)) { log.trace("Found SEC_USER table"); found = true; } } return found; } catch (SQLException e) { throw new DbInitializationException(true, "Error connecting to database: " + e.getMessage(), e); } finally { if (connection != null) try { connection.close(); } catch (SQLException ignored) { } } }
From source file:com.manydesigns.portofino.model.database.ConnectionProvider.java
public void init(DatabasePlatformsRegistry databasePlatformsRegistry) { Connection conn = null; ResultSet typeRs = null;//from w w w . ja v a2 s .c o m String databaseName = getDatabase().getDatabaseName(); try { conn = acquireConnection(); DatabaseMetaData metadata = conn.getMetaData(); databaseProductName = metadata.getDatabaseProductName(); databaseProductVersion = metadata.getDatabaseProductVersion(); try { databaseMajorVersion = metadata.getDatabaseMajorVersion(); databaseMinorVersion = metadata.getDatabaseMinorVersion(); databaseMajorMinorVersion = MessageFormat.format("{0}.{1}", databaseMajorVersion, databaseMinorVersion); } catch (SQLException e) { databaseMajorMinorVersion = e.getMessage(); } driverName = metadata.getDriverName(); driverVersion = metadata.getDriverVersion(); driverMajorVersion = metadata.getDriverMajorVersion(); driverMinorVersion = metadata.getDriverMinorVersion(); driverMajorMinorVersion = MessageFormat.format("{0}.{1}", driverMajorVersion, driverMinorVersion); try { JDBCMajorVersion = metadata.getJDBCMajorVersion(); JDBCMinorVersion = metadata.getJDBCMinorVersion(); JDBCMajorMinorVersion = MessageFormat.format("{0}.{1}", JDBCMajorVersion, JDBCMinorVersion); } catch (Throwable e) { JDBCMajorMinorVersion = e.getMessage(); } // extract supported types types.clear(); typeRs = metadata.getTypeInfo(); while (typeRs.next()) { readType(typeRs); } fixMissingTypeAliases(types); Collections.sort(types, new TypeComparator()); databasePlatform = databasePlatformsRegistry.findApplicableAbstraction(this); if (databasePlatform == null) { status = STATUS_ERROR; errorMessage = MessageFormat.format("Database platform not found for {0}", databaseProductName); logger.warn(errorMessage); } else { status = STATUS_CONNECTED; errorMessage = null; } } catch (Throwable e) { status = STATUS_ERROR; errorMessage = e.getMessage(); logger.warn("Could not create database platform for " + databaseName, e); } finally { DbUtil.closeResultSetAndStatement(typeRs); releaseConnection(conn); lastTested = new Date(); } }
From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java
@Override public void duplicateLayerTable(final String sourceTable, final String destinationTable) { SessionFactoryImplementor sfi = (SessionFactoryImplementor) getSessionFactory(); final String schema = sfi.getSettings().getDefaultSchemaName(); final String copyTableSql = MessageFormat.format(DUPLICATE_TABLE_SQL, schema, destinationTable, sourceTable);//from ww w . j a v a 2s. c om final String updateGeometryColumnSql = String.format(UPDATE_GEOMETRY_COLUMN_SQL, destinationTable, sourceTable); getSession().doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); stmt.execute(copyTableSql); stmt.execute(updateGeometryColumnSql); ResultSet pksRS = connection.getMetaData().getPrimaryKeys(null, schema, sourceTable); if (pksRS.first()) { String primaryKey = pksRS.getString("COLUMN_NAME"); String createPkSql = MessageFormat.format(ADD_TABLE_PK, schema, destinationTable, primaryKey); stmt.execute(createPkSql); } } }); getSession().flush(); }
From source file:com.seer.datacruncher.spring.SchemaFieldsPopupUpdateController.java
private void addLinkedTableFields(SchemaFieldEntity rootEntity, String tableName) { try {/*from w ww .j av a2 s. c o m*/ Connection connection = getConnection(String.valueOf(rootEntity.getIdSchema()), true); md = connection.getMetaData(); ArrayNode childArrayNode = objectMapper.createArrayNode(); ObjectNode parentObjectNode = getNode(catalogueName, DbFieldType.ROOT_FOLDER); ObjectNode node = getNode(tableName, DbFieldType.FOLDER); childFields(node, tableName, rootEntity); node.put("id", tableName); childArrayNode.add(node); parentObjectNode.put("children", childArrayNode); parentObjectNode.put("expanded", true); } catch (SQLException sqex) { sqex.printStackTrace(); } }
From source file:net.ontopia.topicmaps.db2tm.JDBCDataSource.java
@Override public Collection<Relation> getRelations() { Collection<Relation> relations = new ArrayList<Relation>(); Connection c = getConnection(); try {//from w w w. jav a 2 s.c o m DatabaseMetaData dbm = c.getMetaData(); ResultSet rs = dbm.getTables(catalog, schemaPattern, tableNamePattern, new String[] { "TABLE", "VIEW", "SYSTEM TABLE" }); while (rs.next()) { String schema_name = rs.getString(2); String table_name = rs.getString(3); Relation relation = null; if (schema_name != null) relation = mapping.getRelation(schema_name + "." + table_name); if (relation == null) relation = mapping.getRelation(table_name); if (relation == null) relation = mapping.getRelation(table_name.toLowerCase()); if (relation != null) relations.add(relation); else log.debug("No mapping found for table '{}' in schema '{}'.", table_name, schema_name); } rs.close(); } catch (Throwable t) { throw new OntopiaRuntimeException(t); } return relations; }
From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java
@Test public void testInfo() throws Exception { Connection conn = new MyProxy(); try {/*from w ww. j a v a 2 s .c o m*/ try { conn.getMetaData(); } catch (SQLException e) { } try { conn.setCatalog(conn.getCatalog()); } catch (SQLException e) { } try { conn.setReadOnly(conn.isReadOnly()); } catch (SQLException e) { } try { conn.setTransactionIsolation(conn.getTransactionIsolation()); } catch (SQLException e) { } try { conn.setTransactionIsolation(conn.getTransactionIsolation()); } catch (SQLException e) { } try { conn.getWarnings(); } catch (SQLException e) { } try { conn.clearWarnings(); } catch (SQLException e) { } try { conn.setHoldability(conn.getHoldability()); } catch (SQLException e) { } try { conn.setSchema(conn.getSchema()); } catch (SQLException e) { } } finally { JdbcUtil.closeQuietly(conn); } }