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:com.emr.schemas.EditMappingsForm.java
/** * Returns the name of a database from a Connection object * @param con {@link Connection} The connection object * @return {@link String} The database name *///from w w w . ja v a 2s .c o m private String getDatabaseName(Connection con) { String dbName = ""; try { String url = con.getMetaData().getURL(); dbName = url.substring(url.lastIndexOf("/") + 1, url.length()); } catch (SQLException ex) { Logger.getLogger(EditMappingsForm.class.getName()).log(Level.SEVERE, null, ex); } return dbName; }
From source file:com.seer.datacruncher.spring.SchemaFieldsPopupUpdateController.java
private void deleteLinkedTableFields(SchemaFieldEntity fieldEntity, String tableName) { try {/*from w ww .j a v a 2 s . com*/ Connection connection = getConnection(String.valueOf(fieldEntity.getIdSchema()), true); DatabaseMetaData md = connection.getMetaData(); ResultSet rs = md.getColumns(null, null, tableName, null); List<SchemaFieldEntity> listSchemaFields = schemaFieldsDao .findAllByParentId(fieldEntity.getIdSchemaField()); while (rs.next()) { String colName = rs.getString("COLUMN_NAME"); String linkToDb = tableName + "." + colName; if (listSchemaFields != null) { for (SchemaFieldEntity instance : listSchemaFields) { if (colName.equals(instance.getName()) && instance.getLinkToDb().equals(linkToDb)) { delete(instance.getIdSchemaField()); break; } } } } } catch (SQLException sqex) { sqex.printStackTrace(); } }
From source file:de.tu_berlin.dima.oligos.db.JdbcConnector.java
/** * Returns a new JdbcConnector wrapping the connection and caches the * database meta data from the connection. * @param connection/*ww w. j a v a2s. c om*/ * @throws SQLException if there occurs an error while retrieving the database * meta data through the connection. * @since 0.3.1 */ public JdbcConnector(final Connection connection) throws SQLException { this.connection = connection; this.metaData = connection.getMetaData(); }
From source file:net.solarnetwork.node.dao.jdbc.AbstractJdbcDao.java
/** * Test if a table exists in the database. * // w w w . j ava2 s. co m * @param conn * the connection * @param aSchemaName * the schema name to look for (or <em>null</em> for any schema) * @param aTableName * the table name to look for * @return boolean if table is found * @throws SQLException * if any SQL error occurs */ protected boolean tableExists(Connection conn, String aSchemaName, String aTableName) throws SQLException { DatabaseMetaData dbMeta = conn.getMetaData(); ResultSet rs = null; try { rs = dbMeta.getTables(null, null, null, null); while (rs.next()) { String schema = rs.getString(2); String table = rs.getString(3); if ((aSchemaName == null || (aSchemaName.equalsIgnoreCase(schema))) && aTableName.equalsIgnoreCase(table)) { if (log.isDebugEnabled()) { log.debug("Found table " + schema + '.' + table); } return true; } } return false; } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { // ignore this } } } }
From source file:com.netspective.axiom.sql.StoredProcedure.java
/** * Gets the stored procedure's metadata information from the database. This will search * all available catalogs and schemas. This method will ONLY return the metadata of the * stored procedure only when the <i>procedure-name</i> attribute is set in the XML declaration. *//*w w w .jav a 2s .co m*/ public String getMetaData(ConnectionContext cc) throws NamingException, SQLException { // TODO : Using this metadata, we can determine what variables are in and out so that the developer doesn't even have to set it in XML // but currently the procedure-name attribute isn't required but the 'type' attribute is required. If we go the // metadata route we need to change some handling to accept setting the 'type' and if it's not set, we can use // the metadata to get the param type StringBuffer sb = new StringBuffer(); if (procedureName != null && procedureName.length() > 0) { // Get DatabaseMetaData Connection connection = cc.getConnection(); DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getProcedureColumns(null, null, procedureName, "%"); // Printout table data while (rs.next()) { // Get procedure metadata String dbProcedureCatalog = rs.getString(1); String dbProcedureSchema = rs.getString(2); String dbProcedureName = rs.getString(3); String dbColumnName = rs.getString(4); short dbColumnReturn = rs.getShort(5); String dbColumnReturnTypeName = rs.getString(7); int dbColumnPrecision = rs.getInt(8); int dbColumnByteLength = rs.getInt(9); short dbColumnScale = rs.getShort(10); short dbColumnRadix = rs.getShort(11); String dbColumnRemarks = rs.getString(13); // Interpret the return type (readable for humans) String procReturn; switch (dbColumnReturn) { case DatabaseMetaData.procedureColumnIn: procReturn = "In"; break; case DatabaseMetaData.procedureColumnOut: procReturn = "Out"; break; case DatabaseMetaData.procedureColumnInOut: procReturn = "In/Out"; break; case DatabaseMetaData.procedureColumnReturn: procReturn = "return value"; break; case DatabaseMetaData.procedureColumnResult: procReturn = "return ResultSet"; default: procReturn = "Unknown"; } // Printout sb.append("Procedure: " + dbProcedureCatalog + "." + dbProcedureSchema + "." + dbProcedureName); sb.append(" ColumnName [ColumnType(ColumnPrecision)]: " + dbColumnName + " [" + dbColumnReturnTypeName + "(" + dbColumnPrecision + ")]"); sb.append(" ColumnReturns: " + procReturn + "(" + dbColumnReturnTypeName + ")"); sb.append(" Radix: " + dbColumnRadix + ", Scale: " + dbColumnScale); sb.append(" Remarks: " + dbColumnRemarks); } rs.close(); connection.close(); } return sb.toString(); }
From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java
@Override public void deleteQueryValue(ISQLQuery query, ISQLRowResult row) throws SQLException { ISQLRowModificationStatus status = computeRowModificationStatus(query, row, -1); if (status.isModifiable()) { final ISQLResult result = query.getResult(); final Connection conn = query.getConnection(); final DatabaseMetaData md = conn.getMetaData(); final String deleteStmt = buildDeleteStatement(status, md.getIdentifierQuoteString()); PreparedStatement stmt = null; try {/*from ww w .java 2s. c o m*/ stmt = conn.prepareStatement(deleteStmt); fillPreparedStatement(stmt, false, false, row, null); stmt.execute(); if (stmt.getUpdateCount() > 0) { result.removeRow(row); } } finally { if (stmt != null) { stmt.close(); } } } }
From source file:com.nextep.designer.sqlgen.ui.editors.SQLEditor.java
/** * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#dispose() *///from w w w . j a va 2s . c om @Override public void dispose() { Designer.getListenerService().unregisterListeners(this); IEditorInput input = getEditorInput(); if (input instanceof IConnectable) { final IConnectable connectableInput = (IConnectable) input; Connection conn = connectableInput.getSqlConnection(); if (conn != null) { try { final DatabaseMetaData md = conn.getMetaData(); log.info("Disconnecting from " + md.getURL()); conn.close(); connectableInput.setSqlConnection(null); } catch (SQLException e) { log.warn("Unable to close connection: " + e.getMessage(), e); } } } super.dispose(); }
From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java
@Override public ISQLRowModificationStatus updateQueryValue(ISQLQuery query, ISQLRowResult row, int modifiedColumnIndex, Object newValue) throws SQLException { final Connection conn = query.getConnection(); final DatabaseMetaData md = conn.getMetaData(); // For pending rows, we set the new column value if (row.isPending()) { row.setValue(modifiedColumnIndex, newValue); }//from www . ja v a 2 s. c o m final ISQLRowModificationStatus status = computeRowModificationStatus(query, row, modifiedColumnIndex); // Now processing database update if we can if (status.isModifiable()) { // Now we can build our query String sqlStatement = null; final boolean insertNeeded = status.isInsertNeeded(); if (insertNeeded) { sqlStatement = buildInsertStatement(status, md.getIdentifierQuoteString()); } else { sqlStatement = buildUpdateStatement(status, md.getIdentifierQuoteString()); } PreparedStatement stmt = null; try { stmt = conn.prepareStatement(sqlStatement); fillPreparedStatement(stmt, !insertNeeded, insertNeeded, row, newValue); stmt.execute(); // Everything was OK, we can unflag any pending row if (row.isPending()) { row.setPending(false); } } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { LOGGER.error("Unable to close SQL update statement: " + e.getMessage(), e); } } } } return status; }
From source file:net.ontopia.topicmaps.db2tm.JDBCDataSource.java
private Map<String, Integer> getColumnTypes(String schema, String table, Connection conn) throws SQLException { Map<String, Integer> datatypes = new HashMap<String, Integer>(); ResultSet rs = conn.getMetaData().getColumns(null, null, table, null); try {/*from www .ja va 2s. c om*/ while (rs.next()) // 4: COLUMN_NAME // 5: DATA_TYPE datatypes.put(rs.getString(4), new Integer(rs.getInt(5))); } finally { rs.close(); } // sometimes the above doesn't produce any results, because some // implementations require uppercase table names here if (datatypes.isEmpty()) { // try with uppercase rs = conn.getMetaData().getColumns(null, null, table.toUpperCase(), null); try { while (rs.next()) { datatypes.put(rs.getString(4), new Integer(rs.getInt(5))); } } finally { rs.close(); } } return datatypes; }
From source file:de.hybris.platform.virtualjdbc.jalo.AbstractVjdbcSqlTest.java
protected void selectTest(final Connection vjdbcCon) throws Exception { final String tablePrefix = Registry.getCurrentTenant().equals(Registry.getMasterTenant()) ? "" : Registry.getCurrentTenant().getTenantID() + "_"; String realQuery = String.format(QUERY_FIND_PRODUCTS, StringUtils.isEmpty(tablePrefix) ? "" : tablePrefix); realQuery = realQuery + CONDITION;/*from w ww . ja v a2 s.c om*/ Statement stmt = null; ResultSet res = null; try { verifyUnderlyingConnection(vjdbcCon); stmt = vjdbcCon.createStatement(); LOG.info("Underlying data base url:: " + vjdbcCon.getMetaData().getURL()); LOG.info("Executing query:: " + realQuery); res = stmt.executeQuery(realQuery);//stmt.getResultSet(); int idx = 0; if (res != null) { while (res.next()) { ++idx; if (LOG.isDebugEnabled()) { LOG.debug("result[" + (idx) + "]:" + res.getString(1)); } Assert.assertTrue(res.getString(1).startsWith(PRODUCT_PREFIX)); } } Assert.assertTrue("Should get " + PRODUCT_COUNT + " instead of " + idx, idx == PRODUCT_COUNT); } finally { Utilities.tryToCloseJDBC(vjdbcCon, stmt, res); } }