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:edu.mayo.informatics.cts.CTSVAPI.sql.refImpl.SQLStatements.java
private SQLStatements(String username, String password, String url, String driver, String tablePrefix) throws Exception { logger_.debug("Initializing sql and sql connections"); JDBCConnectionDescriptor desc = getConnectionDescriptor(); try {//from w ww . j a v a 2s . c om desc.setDbDriver(driver); } catch (ClassNotFoundException e) { logger_.error("The driver for your sql connection was not found. I tried to load " + driver); throw e; } desc.setDbUid(username); desc.setDbPwd(password); desc.setAutoCommit(true); desc.setDbUrl(url); desc.setUseUTF8(true); desc.setAutoRetryFailedConnections(true); // Connection pool parameters JDBCConnectionPoolPolicy pol = getConnectionPoolPolicy(); pol.maxActive = 4; pol.maxIdle = -1; pol.maxWait = -1; pol.minEvictableIdleTimeMillis = -1; pol.numTestsPerEvictionRun = 1; pol.testOnBorrow = false; pol.testOnReturn = false; pol.testWhileIdle = false; pol.timeBetweenEvictionRunsMillis = -1; pol.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW; desc.setPingSQL("Select CodingSchemeName from codingScheme where CodingSchemeName='foobar'"); // I need to know this to generate proper queries. Connection conn = (Connection) getConnectionPool().borrowObject(); String databaseName = conn.getMetaData().getDatabaseProductName(); stc_ = new SQLTableUtilities(conn, tablePrefix).getSQLTableConstants(); getConnectionPool().returnObject(conn); //need to override the like since the converter now creates case sensitive tables //this forces a case insensitive search GenericSQLModifier.mySqlLikeOverride = "COLLATE latin1_swedish_ci LIKE"; gSQLMod_ = new GenericSQLModifier(databaseName, false); initStatements(); }
From source file:com.stratelia.webactiv.util.DBUtil.java
/** * Gets all table names./*from w ww .ja va 2 s. com*/ * @return */ public static Set<String> getAllTableNames() { Connection privateConnection = null; ResultSet tables_rs = null; boolean testingMode = false; Set<String> tableNames = new LinkedHashSet<String>(); try { // On ne peux pas utiliser une simple connection du pool // on utilise une connection extrieure au contexte transactionnel des ejb synchronized (DBUtil.class) { if (getInstance().connectionForTest != null) { privateConnection = getInstance().connectionForTest; testingMode = true; } else { privateConnection = ConnectionPool.getConnection(); } } DatabaseMetaData dbMetaData = privateConnection.getMetaData(); tables_rs = dbMetaData.getTables(null, null, null, null); tables_rs.getMetaData(); while (tables_rs.next()) { tableNames.add(tables_rs.getString(TABLE_NAME)); } } catch (Exception e) { SilverTrace.debug("util", "DBUtil.getAllTableNames", "database error ...", e); } finally { close(tables_rs); if (privateConnection != null && !testingMode) { close(privateConnection); } } return tableNames; }
From source file:net.certifi.audittablegen.AuditTableGen.java
/** * Examines the DataSource metadata for information pertaining to the * driver, catalog, schema and the presence of audit table configuration * data.//from www. j a va 2s . c o m * * @return String containing datasource information. * @throws SQLException */ String getDataSourceInfo() throws SQLException { Connection conn = dataSource.getConnection(); DatabaseMetaData dmd = conn.getMetaData(); StringBuilder s = new StringBuilder(); s.append("Driver Name: ").append(dmd.getDriverName()).append("Driver Version: ") .append(dmd.getDriverVersion()).append(System.lineSeparator()).append("CatalogSeperator: ") .append(dmd.getCatalogSeparator()).append(System.lineSeparator()).append("CatalogTerm: ") .append(dmd.getCatalogTerm()).append(System.lineSeparator()).append("SchemaTerm: ") .append(dmd.getSchemaTerm()).append(System.lineSeparator()).append("Catalogs: "); ResultSet rs = dmd.getCatalogs(); while (rs.next()) { s.append(rs.getString("TABLE_CAT")).append(","); logger.debug("Catalog: {}", rs.getString("TABLE_CAT")); } rs.close(); s.append(System.lineSeparator()); s.append("Schemas: "); rs = dmd.getSchemas(); while (rs.next()) { logger.debug("Schema: {}", rs.getString("TABLE_SCHEM")); s.append("{catalog}:").append(rs.getString("TABLE_CATALOG")).append(" {schema}:") .append(rs.getString("TABLE_SCHEM")).append(","); } rs.close(); s.append(System.lineSeparator()).append("Target Catalog: ").append(catalog).append(System.lineSeparator()) .append("Target Schema: ").append(schema).append(System.lineSeparator()); // if (dmr.hasAuditConfigTable()){ // s.append("Has auditConfigSource table").append(System.lineSeparator()); // } conn.close(); return s.toString(); }
From source file:com.thinkbiganalytics.schema.DBSchemaParser.java
private Set<String> listPrimaryKeys(Connection conn, String schema, String tableName) throws SQLException { HashSet<String> primaryKeys = new HashSet<>(); try (ResultSet rs = conn.getMetaData().getPrimaryKeys(null, schema, tableName)) { while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); primaryKeys.add(columnName); }// w ww. ja va 2 s . c om } catch (SQLException e) { //attempt to use the catalog instead of the schema try (ResultSet rs = conn.getMetaData().getPrimaryKeys(schema, null, tableName)) { while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); primaryKeys.add(columnName); } } catch (SQLException e2) { log.info("Failed to list primary keys of {}.{}", schema, tableName); } } return primaryKeys; }
From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataStructureHandler.java
@Override public <E> boolean isDefined(TableMetadata<E> tableMetadata) { try {// ww w . ja v a 2s . c om final Connection connection = session.getConnection(); final boolean result = session.getDatabaseDialect().hasTable(connection.getMetaData(), tableMetadata); connection.close(); return result; } catch (SQLException e) { throw new UnsuccessfulOperationError("Failed to check definition for table", e); } }
From source file:ViewDB.java
public ViewDBFrame() { setTitle("ViewDB"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); tableNames = new JComboBox(); tableNames.addActionListener(new ActionListener() {//from ww w .j av a2 s . c o m public void actionPerformed(ActionEvent event) { showTable((String) tableNames.getSelectedItem()); } }); add(tableNames, BorderLayout.NORTH); try { readDatabaseProperties(); Connection conn = getConnection(); try { DatabaseMetaData meta = conn.getMetaData(); ResultSet mrs = meta.getTables(null, null, null, new String[] { "TABLE" }); while (mrs.next()) tableNames.addItem(mrs.getString(3)); } finally { conn.close(); } } catch (SQLException e) { JOptionPane.showMessageDialog(this, e); } catch (IOException e) { JOptionPane.showMessageDialog(this, e); } JPanel buttonPanel = new JPanel(); add(buttonPanel, BorderLayout.SOUTH); previousButton = new JButton("Previous"); previousButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { showPreviousRow(); } }); buttonPanel.add(previousButton); nextButton = new JButton("Next"); nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { showNextRow(); } }); buttonPanel.add(nextButton); deleteButton = new JButton("Delete"); deleteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { deleteRow(); } }); buttonPanel.add(deleteButton); saveButton = new JButton("Save"); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { saveChanges(); } }); buttonPanel.add(saveButton); }
From source file:net.hydromatic.optiq.impl.jdbc.JdbcSchema.java
private ImmutableMap<String, JdbcTable> computeTables() { Connection connection = null; ResultSet resultSet = null;/*from w ww .j a v a 2 s . co m*/ try { connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); resultSet = metaData.getTables(catalog, schema, null, null); final ImmutableMap.Builder<String, JdbcTable> builder = ImmutableMap.builder(); while (resultSet.next()) { final String tableName = resultSet.getString(3); final String catalogName = resultSet.getString(1); final String schemaName = resultSet.getString(2); final String tableTypeName = resultSet.getString(4); final TableType tableType = Util.enumVal(TableType.class, tableTypeName); final JdbcTable table = new JdbcTable(this, catalogName, schemaName, tableName, tableType); builder.put(tableName, table); } return builder.build(); } catch (SQLException e) { throw new RuntimeException("Exception while reading tables", e); } finally { close(connection, null, resultSet); } }
From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java
public String getDatabaseType() { if (databaseType != null) { return databaseType; }/*from w w w. ja v a 2 s.c o m*/ try { @SuppressWarnings("deprecation") Connection connection = sessionFactory.getCurrentSession().connection(); DatabaseMetaData metaData = connection.getMetaData(); databaseType = metaData.getDatabaseProductName(); if (databaseType.equals("Apache Derby")) { return databaseType = "derby"; } else if (databaseType.equals("MySQL")) { return databaseType = "mysql"; } else if (databaseType.equals("PostgreSQL")) { return databaseType = "postgres"; } else if (databaseType.equals("Microsoft SQL Server")) { return databaseType = "mssql"; } else { log.info(databaseType + " is not a supported database type"); } } catch (HibernateException e) { log.error("Could not determine database type", e); } catch (SQLException e) { log.error("Could not determine database type", e); } return "unknown"; }
From source file:azkaban.database.AzkabanDatabaseSetup.java
private void loadInstalledTables() throws SQLException { logger.info("Searching for installed tables"); Connection conn = null; try {//from w w w . j av a 2 s . com conn = dataSource.getConnection(); ResultSet rs = conn.getMetaData().getTables(conn.getCatalog(), null, null, new String[] { "TABLE" }); while (rs.next()) { tables.put(rs.getString("TABLE_NAME").toLowerCase(), "2.1"); } } finally { DbUtils.commitAndCloseQuietly(conn); } }
From source file:de.erdesignerng.dialect.msaccess.MSAccessFileFormat.java
/** * Reads the version of the engine from the binary and searches for special * system tables throuph the connection to classifie the version more * detailled./* w ww .j a v a 2 s .co m*/ * <p/> * Attention: Access 2002 and 2003 still *not* be devided! * * @see http://msdn.microsoft.com/en-us/library/aa139959%28office.10%29.aspx */ public final boolean matches(Connection aConnection) { String theFile = null; boolean theResult = false; // get specifiled database file from the connection URL try { String[] theParamArray = aConnection.getMetaData().getURL().split(";"); for (int i = 0; i < theParamArray.length; i++) { if (theParamArray[i].toUpperCase().startsWith("DBQ")) { theParamArray = theParamArray[i].split("="); theFile = theParamArray[1]; break; } } if (!StringUtils.isEmpty(theFile)) { // evaluate the engine information theResult = matches(theFile, false); // additionally search the database for a special tablename if (theResult && !StringUtils.isEmpty(theIdentifyingTable)) { theResult = (getTableCount(aConnection, theIdentifyingTable) == 1); } } } catch (SQLException e) { } return theResult; }