List of usage examples for java.sql ResultSetMetaData getPrecision
int getPrecision(int column) throws SQLException;
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java
public List<ColumnVO> getColumnsMetaDataExceptGeom(String sql, String geometryName) throws Exception { Exception error = null;/*from ww w . j a v a 2 s.co m*/ List<ColumnVO> tableColumns = new LinkedList<ColumnVO>(); Connection connection = null; PreparedStatement preparedStmnt = null; try { DataSource dataSource = poolDataSources.get(schemaId); connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStmnt = connection.prepareStatement(sql); ResultSet rs = preparedStmnt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); String geometryFieldName = geometryName; if (StringUtils.isEmpty(geometryFieldName)) { geometryFieldName = "the_geom"; } for (int i = 1; i <= rsmd.getColumnCount(); i++) { String columnName = rsmd.getColumnName(i); if (!columnName.equals(geometryFieldName)) { String columnType = rsmd.getColumnTypeName(i); int columnSqlType = rsmd.getColumnType(i); int columnLength = rsmd.getColumnDisplaySize(i); int columnPrecision = rsmd.getPrecision(i); ColumnVO column = new ColumnVO(); column.setNameOnTable(columnName); column.setType(columnType); column.setSqlType(columnSqlType); column.setLength(columnLength); column.setPrecision(columnPrecision); column.setInTable(true); tableColumns.add(column); } } } catch (SQLException e) { error = e; } finally { if (preparedStmnt != null) { try { preparedStmnt.close(); } catch (SQLException se2) { log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage())); } } if (connection != null) { try { if (error != null) { connection.rollback(); } } catch (SQLException se) { log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage())); } try { connection.close(); } catch (SQLException se) { log.warn("Se produjo un error al intentar cerrar la conexin: " .concat(se.getLocalizedMessage())); } } } if (error != null) { throw error; } return tableColumns; }
From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java
public void testResultSetMetaData() throws SQLException { Statement stmt = con.createStatement(); ResultSet res = stmt.executeQuery("select c1, c2, c3, c4, c5 as a, c6, c7, c8, c9, c10, c11, c12, " + "c1*2, sentences(null, null, null) as b, c17, c18, c20 from " + dataTypeTableName + " limit 1"); ResultSetMetaData meta = res.getMetaData(); ResultSet colRS = con.getMetaData().getColumns(null, null, dataTypeTableName.toLowerCase(), null); assertEquals(17, meta.getColumnCount()); assertTrue(colRS.next());/*w ww . j a v a 2s . co m*/ assertEquals("c1", meta.getColumnName(1)); assertEquals(Types.INTEGER, meta.getColumnType(1)); assertEquals("int", meta.getColumnTypeName(1)); assertEquals(11, meta.getColumnDisplaySize(1)); assertEquals(10, meta.getPrecision(1)); assertEquals(0, meta.getScale(1)); assertEquals("c1", colRS.getString("COLUMN_NAME")); assertEquals(Types.INTEGER, colRS.getInt("DATA_TYPE")); assertEquals("int", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(1), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(1), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c2", meta.getColumnName(2)); assertEquals("boolean", meta.getColumnTypeName(2)); assertEquals(Types.BOOLEAN, meta.getColumnType(2)); assertEquals(1, meta.getColumnDisplaySize(2)); assertEquals(1, meta.getPrecision(2)); assertEquals(0, meta.getScale(2)); assertEquals("c2", colRS.getString("COLUMN_NAME")); assertEquals(Types.BOOLEAN, colRS.getInt("DATA_TYPE")); assertEquals("boolean", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(2), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(2), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c3", meta.getColumnName(3)); assertEquals(Types.DOUBLE, meta.getColumnType(3)); assertEquals("double", meta.getColumnTypeName(3)); assertEquals(25, meta.getColumnDisplaySize(3)); assertEquals(15, meta.getPrecision(3)); assertEquals(15, meta.getScale(3)); assertEquals("c3", colRS.getString("COLUMN_NAME")); assertEquals(Types.DOUBLE, colRS.getInt("DATA_TYPE")); assertEquals("double", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(3), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(3), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c4", meta.getColumnName(4)); assertEquals(Types.VARCHAR, meta.getColumnType(4)); assertEquals("string", meta.getColumnTypeName(4)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(4)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(4)); assertEquals(0, meta.getScale(4)); assertEquals("c4", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("string", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(4), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(4), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("a", meta.getColumnName(5)); assertEquals(Types.VARCHAR, meta.getColumnType(5)); assertEquals("string", meta.getColumnTypeName(5)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(5)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(5)); assertEquals(0, meta.getScale(5)); assertEquals("c5", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("array<int>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(5), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(5), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c6", meta.getColumnName(6)); assertEquals(Types.VARCHAR, meta.getColumnType(6)); assertEquals("string", meta.getColumnTypeName(6)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(6)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(6)); assertEquals(0, meta.getScale(6)); assertEquals("c6", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("map<int,string>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(6), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(6), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c7", meta.getColumnName(7)); assertEquals(Types.VARCHAR, meta.getColumnType(7)); assertEquals("string", meta.getColumnTypeName(7)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(7)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(7)); assertEquals(0, meta.getScale(7)); assertEquals("c7", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("map<string,string>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(7), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(7), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c8", meta.getColumnName(8)); assertEquals(Types.VARCHAR, meta.getColumnType(8)); assertEquals("string", meta.getColumnTypeName(8)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(8)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(8)); assertEquals(0, meta.getScale(8)); assertEquals("c8", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("struct<r:string,s:int,t:double>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(8), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(8), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c9", meta.getColumnName(9)); assertEquals(Types.TINYINT, meta.getColumnType(9)); assertEquals("tinyint", meta.getColumnTypeName(9)); assertEquals(4, meta.getColumnDisplaySize(9)); assertEquals(3, meta.getPrecision(9)); assertEquals(0, meta.getScale(9)); assertEquals("c9", colRS.getString("COLUMN_NAME")); assertEquals(Types.TINYINT, colRS.getInt("DATA_TYPE")); assertEquals("tinyint", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(9), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(9), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c10", meta.getColumnName(10)); assertEquals(Types.SMALLINT, meta.getColumnType(10)); assertEquals("smallint", meta.getColumnTypeName(10)); assertEquals(6, meta.getColumnDisplaySize(10)); assertEquals(5, meta.getPrecision(10)); assertEquals(0, meta.getScale(10)); assertEquals("c10", colRS.getString("COLUMN_NAME")); assertEquals(Types.SMALLINT, colRS.getInt("DATA_TYPE")); assertEquals("smallint", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(10), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(10), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c11", meta.getColumnName(11)); assertEquals(Types.FLOAT, meta.getColumnType(11)); assertEquals("float", meta.getColumnTypeName(11)); assertEquals(24, meta.getColumnDisplaySize(11)); assertEquals(7, meta.getPrecision(11)); assertEquals(7, meta.getScale(11)); assertEquals("c11", colRS.getString("COLUMN_NAME")); assertEquals(Types.FLOAT, colRS.getInt("DATA_TYPE")); assertEquals("float", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(11), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(11), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c12", meta.getColumnName(12)); assertEquals(Types.BIGINT, meta.getColumnType(12)); assertEquals("bigint", meta.getColumnTypeName(12)); assertEquals(20, meta.getColumnDisplaySize(12)); assertEquals(19, meta.getPrecision(12)); assertEquals(0, meta.getScale(12)); assertEquals("c12", colRS.getString("COLUMN_NAME")); assertEquals(Types.BIGINT, colRS.getInt("DATA_TYPE")); assertEquals("bigint", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(12), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(12), colRS.getInt("DECIMAL_DIGITS")); assertEquals("_c12", meta.getColumnName(13)); assertEquals(Types.INTEGER, meta.getColumnType(13)); assertEquals("int", meta.getColumnTypeName(13)); assertEquals(11, meta.getColumnDisplaySize(13)); assertEquals(10, meta.getPrecision(13)); assertEquals(0, meta.getScale(13)); assertEquals("b", meta.getColumnName(14)); assertEquals(Types.VARCHAR, meta.getColumnType(14)); assertEquals("string", meta.getColumnTypeName(14)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(14)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(14)); assertEquals(0, meta.getScale(14)); assertEquals("c17", meta.getColumnName(15)); assertEquals(Types.TIMESTAMP, meta.getColumnType(15)); assertEquals("timestamp", meta.getColumnTypeName(15)); assertEquals(29, meta.getColumnDisplaySize(15)); assertEquals(29, meta.getPrecision(15)); assertEquals(9, meta.getScale(15)); assertEquals("c18", meta.getColumnName(16)); assertEquals(Types.DECIMAL, meta.getColumnType(16)); assertEquals("decimal", meta.getColumnTypeName(16)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(16)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(16)); assertEquals(Integer.MAX_VALUE, meta.getScale(16)); assertEquals("c20", meta.getColumnName(17)); assertEquals(Types.DATE, meta.getColumnType(17)); assertEquals("date", meta.getColumnTypeName(17)); assertEquals(10, meta.getColumnDisplaySize(17)); assertEquals(10, meta.getPrecision(17)); assertEquals(0, meta.getScale(17)); for (int i = 1; i <= meta.getColumnCount(); i++) { assertFalse(meta.isAutoIncrement(i)); assertFalse(meta.isCurrency(i)); assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(i)); } }
From source file:edu.ku.brc.specify.conversion.ConvertTaxonHelper.java
/** ============================================================================= * Convert Taxon//from w ww .j a v a2 s . c om * ============================================================================= */ private void convertTaxonRecords() { txMapper = IdMapperMgr.getInstance().get("taxonname", "TaxonNameID"); txTypMapper = IdMapperMgr.getInstance().get("TaxonomyType", "TaxonomyTypeID"); txUnitTypMapper = IdMapperMgr.getInstance().get("TaxonomicUnitType", "TaxonomicUnitTypeID"); mappers = new IdMapperIFace[] { txMapper, txMapper, txTypMapper, txMapper, txUnitTypMapper }; IdHashMapper.setTblWriter(tblWriter); newToOldColMap.put("TaxonID", "TaxonNameID"); newToOldColMap.put("ParentID", "ParentTaxonNameID"); newToOldColMap.put("TaxonTreeDefID", "TaxonomyTypeID"); newToOldColMap.put("TaxonTreeDefItemID", "TaxonomicUnitTypeID"); newToOldColMap.put("Name", "TaxonName"); newToOldColMap.put("FullName", "FullTaxonName"); newToOldColMap.put("IsAccepted", "Accepted"); oldToNewColMap.put("TaxonNameID", "TaxonID"); oldToNewColMap.put("ParentTaxonNameID", "ParentID"); oldToNewColMap.put("TaxonomyTypeID", "TaxonTreeDefID"); oldToNewColMap.put("TaxonomicUnitTypeID", "TaxonTreeDefItemID"); oldToNewColMap.put("TaxonName", "Name"); oldToNewColMap.put("FullTaxonName", "FullName"); oldToNewColMap.put("Accepted", "IsAccepted"); // Ignore new fields // These were added for supporting the new security model and hybrids /*String[] ignoredFields = { "GUID", "Visibility", "VisibilitySetBy", "IsHybrid", "HybridParent1ID", "HybridParent2ID", "EsaStatus", "CitesStatus", "UsfwsCode", "IsisNumber", "Text1", "Text2", "NcbiTaxonNumber", "Number1", "Number2", "CreatedByAgentID", "ModifiedByAgentID", "Version", "CultivarName", "LabelFormat", "COLStatus", "VisibilitySetByID"}; */ StringBuilder newSB = new StringBuilder(); StringBuilder vl = new StringBuilder(); for (int i = 0; i < cols.length; i++) { fieldToColHash.put(cols[i], i + 1); colToFieldHash.put(i + 1, cols[i]); if (newSB.length() > 0) newSB.append(", "); newSB.append(cols[i]); if (vl.length() > 0) vl.append(','); vl.append('?'); } StringBuilder oldSB = new StringBuilder(); for (int i = 0; i < oldCols.length; i++) { oldFieldToColHash.put(oldCols[i], i + 1); if (oldSB.length() > 0) oldSB.append(", "); oldSB.append("tx."); oldSB.append(oldCols[i]); } rankIdOldDBInx = oldFieldToColHash.get("RankID"); String sqlStr = String.format("SELECT %s FROM taxon", newSB.toString()); log.debug(sqlStr); String sql = String.format("SELECT %s %s", oldSB.toString(), taxonFromClause); log.debug(sql); String cntSQL = String.format("SELECT COUNT(*) %s", taxonFromClause); log.debug(cntSQL); int txCnt = BasicSQLUtils.getCountAsInt(oldDBConn, cntSQL); if (frame != null) { frame.setProcess(0, txCnt); } String pStr = String.format("INSERT INTO taxon (%s) VALUES (%s)", newSB.toString(), vl.toString()); log.debug(pStr); try { stmtTx = newDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs1 = stmtTx.executeQuery(sqlStr); ResultSetMetaData rsmd1 = rs1.getMetaData(); colTypes = new int[rsmd1.getColumnCount()]; colSizes = new int[rsmd1.getColumnCount()]; for (int i = 0; i < colTypes.length; i++) { colTypes[i] = rsmd1.getColumnType(i + 1); colSizes[i] = rsmd1.getPrecision(i + 1); } rs1.close(); stmtTx.close(); missingParentList.clear(); strandedFixedHash.clear(); lastEditedByInx = oldFieldToColHash.get("LastEditedBy"); modifiedByAgentInx = fieldToColHash.get("ModifiedByAgentID"); stmtTx = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); pStmtTx = newDBConn.prepareStatement(pStr); mappers[1].setShowLogErrors(false); int cnt = 0; ResultSet rs = stmtTx.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { processRow(rs, rsmd, null); cnt++; if (cnt % 1000 == 0) { log.debug(cnt); if (frame != null) { frame.setProcess(cnt); } } } rs.close(); if (frame != null) { frame.setProcess(txCnt, txCnt); } if (missingParentList.size() > 0) { fixStrandedTaxon(oldSB); tblWriter.setHasLines(); tblWriter.startTable("Stranded Taxon (no parent): " + missingParentList.size()); tblWriter.logHdr("Full Name", "RankID", "Sp5 RecordID", "Was Re-parented", "Description"); for (Pair<Integer, String> p : missingParentList) { tblWriter.append("<TR>"); Object[] row = BasicSQLUtils.queryForRow(oldDBConn, "SELECT FullTaxonName, RankID, TaxonNameID FROM taxonname WHERE TaxonNameID = " + p.first); for (Object obj : row) { tblWriter.append("<TD>"); tblWriter.append(obj != null ? obj.toString() : "null"); tblWriter.append("</TD>"); } tblWriter.append("<TD>"); tblWriter.append(strandedFixedHash.contains(p.first) ? "Yes" : "No"); tblWriter.append("</TD><TD>"); tblWriter.append(p.second); tblWriter.append("</TD></TR>"); } tblWriter.endTable(); tblWriter.append("<BR>"); frame.setDesc("Renumbering the tree nodes, this may take a while..."); HashSet<Integer> ttdHash = new HashSet<Integer>(); for (CollectionInfo colInfo : CollectionInfo.getFilteredCollectionInfoList()) { if (!ttdHash.contains(colInfo.getTaxonTreeDef().getId())) { DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance().createSession(); TaxonTreeDef taxonTreeDef = colInfo.getTaxonTreeDef(); taxonTreeDef = (TaxonTreeDef) session .getData("FROM TaxonTreeDef WHERE id = " + taxonTreeDef.getId()); sql = "SELECT TaxonID FROM taxon WHERE RankID = 0 AND TaxonTreeDefID = " + taxonTreeDef.getId(); log.debug(sql); Integer txRootId = BasicSQLUtils.getCount(sql); Taxon txRoot = (Taxon) session.getData("FROM Taxon WHERE id = " + txRootId); NodeNumberer<Taxon, TaxonTreeDef, TaxonTreeDefItem> nodeNumberer = new NodeNumberer<Taxon, TaxonTreeDef, TaxonTreeDefItem>( txRoot.getDefinition()); nodeNumberer.doInBackground(); } catch (Exception ex) { //session.rollback(); ex.printStackTrace(); } finally { if (session != null) { session.close(); } } ttdHash.add(colInfo.getTaxonTreeDef().getId()); } } frame.setDesc("Renumbering done."); } missingParentList.clear(); strandedFixedHash.clear(); } catch (SQLException ex) { ex.printStackTrace(); } finally { try { stmtTx.close(); pStmtTx.close(); } catch (Exception ex) { } } IdHashMapper.setTblWriter(null); }
From source file:org.seasar.dbflute.logic.sql2entity.cmentity.DfCustomizeEntityMetaExtractor.java
public Map<String, DfColumnMeta> extractColumnMetaInfoMap(ResultSet rs, String sql, DfForcedJavaNativeProvider forcedJavaNativeProvider) throws SQLException { final Map<String, DfColumnMeta> columnMetaInfoMap = StringKeyMap.createAsFlexibleOrdered(); final ResultSetMetaData md = rs.getMetaData(); for (int i = 1; i <= md.getColumnCount(); i++) { final DfColumnMeta metaInfo = new DfColumnMeta(); String sql2EntityRelatedTableName = null; try {/* ww w. j a v a 2 s . c o m*/ sql2EntityRelatedTableName = md.getTableName(i); } catch (SQLException ignored) { // Because this table name is not required. This is for classification. String msg = "ResultSetMetaData.getTableName(" + i + ") threw the exception:"; msg = msg + " " + ignored.getMessage(); _log.info(msg); } metaInfo.setSql2EntityRelatedTableName(sql2EntityRelatedTableName); String columnName = md.getColumnLabel(i); final String relatedColumnName = md.getColumnName(i); metaInfo.setSql2EntityRelatedColumnName(relatedColumnName); if (columnName == null || columnName.trim().length() == 0) { columnName = relatedColumnName; } if (columnName == null || columnName.trim().length() == 0) { final String ln = ln(); String msg = "The columnName is invalid: columnName=" + columnName + ln; msg = msg + "ResultSetMetaData returned invalid value." + ln; msg = msg + "sql=" + sql; throw new IllegalStateException(msg); } metaInfo.setColumnName(columnName); final int columnType = md.getColumnType(i); metaInfo.setJdbcDefValue(columnType); final String columnTypeName = md.getColumnTypeName(i); metaInfo.setDbTypeName(columnTypeName); int columnSize = md.getPrecision(i); if (!DfColumnExtractor.isColumnSizeValid(columnSize)) { // ex) sum(COLUMN) columnSize = md.getColumnDisplaySize(i); } metaInfo.setColumnSize(columnSize); final int scale = md.getScale(i); metaInfo.setDecimalDigits(scale); if (forcedJavaNativeProvider != null) { final String sql2entityForcedJavaNative = forcedJavaNativeProvider.provide(columnName); metaInfo.setSql2EntityForcedJavaNative(sql2entityForcedJavaNative); } // column comment is not set here (no comment on meta data) // if select column comment is specified, comment will be set later columnMetaInfoMap.put(columnName, metaInfo); } return columnMetaInfoMap; }
From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ResultSetTableModelFactory.java
/** * No longer used./*from w w w.j a v a2 s . c om*/ * * @param rsmd * @param metaData * @param column */ @Deprecated public static void updateMetaData(final ResultSetMetaData rsmd, final DefaultTableMetaData metaData, final int column) { try { if (rsmd.isCurrency(column + 1)) { metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.CURRENCY, Boolean.TRUE); } else { metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.CURRENCY, Boolean.FALSE); } if (rsmd.isSigned(column + 1)) { metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.SIGNED, Boolean.TRUE); } else { metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.SIGNED, Boolean.FALSE); } final String tableName = rsmd.getTableName(column + 1); if (tableName != null) { metaData.setColumnAttribute(column, MetaAttributeNames.Database.NAMESPACE, MetaAttributeNames.Database.TABLE, tableName); } final String schemaName = rsmd.getSchemaName(column + 1); if (schemaName != null) { metaData.setColumnAttribute(column, MetaAttributeNames.Database.NAMESPACE, MetaAttributeNames.Database.SCHEMA, schemaName); } final String catalogName = rsmd.getCatalogName(column + 1); if (catalogName != null) { metaData.setColumnAttribute(column, MetaAttributeNames.Database.NAMESPACE, MetaAttributeNames.Database.CATALOG, catalogName); } final String label = rsmd.getColumnLabel(column + 1); if (label != null) { metaData.setColumnAttribute(column, MetaAttributeNames.Formatting.NAMESPACE, MetaAttributeNames.Formatting.LABEL, label); } final int displaySize = rsmd.getColumnDisplaySize(column + 1); metaData.setColumnAttribute(column, MetaAttributeNames.Formatting.NAMESPACE, MetaAttributeNames.Formatting.DISPLAY_SIZE, IntegerCache.getInteger(displaySize)); final int precision = rsmd.getPrecision(column + 1); metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.PRECISION, IntegerCache.getInteger(precision)); final int scale = rsmd.getScale(column + 1); metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.SCALE, IntegerCache.getInteger(scale)); } catch (SQLException sqle) { // It is non-fatal if the meta-data cannot be read from the result set. Drivers are // buggy all the time .. } }
From source file:com.openddal.test.BaseTestCase.java
/** * Check if the result set meta data is correct. * * @param rs the result set// www. j a va 2 s .c o m * @param columnCount the expected column count * @param labels the expected column labels * @param datatypes the expected data types * @param precision the expected precisions * @param scale the expected scales */ protected void assertResultSetMeta(ResultSet rs, int columnCount, String[] labels, int[] datatypes, int[] precision, int[] scale) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); int cc = meta.getColumnCount(); if (cc != columnCount) { fail("result set contains " + cc + " columns not " + columnCount); } for (int i = 0; i < columnCount; i++) { if (labels != null) { String l = meta.getColumnLabel(i + 1); if (!labels[i].equals(l)) { fail("column label " + i + " is " + l + " not " + labels[i]); } } if (datatypes != null) { int t = meta.getColumnType(i + 1); if (datatypes[i] != t) { fail("column datatype " + i + " is " + t + " not " + datatypes[i] + " (prec=" + meta.getPrecision(i + 1) + " scale=" + meta.getScale(i + 1) + ")"); } String typeName = meta.getColumnTypeName(i + 1); String className = meta.getColumnClassName(i + 1); switch (t) { case Types.INTEGER: Assert.assertEquals("INTEGER", typeName); Assert.assertEquals("java.lang.Integer", className); break; case Types.VARCHAR: Assert.assertEquals("VARCHAR", typeName); Assert.assertEquals("java.lang.String", className); break; case Types.SMALLINT: Assert.assertEquals("SMALLINT", typeName); Assert.assertEquals("java.lang.Short", className); break; case Types.TIMESTAMP: Assert.assertEquals("TIMESTAMP", typeName); Assert.assertEquals("java.sql.Timestamp", className); break; case Types.DECIMAL: Assert.assertEquals("DECIMAL", typeName); Assert.assertEquals("java.math.BigDecimal", className); break; default: } } if (precision != null) { int p = meta.getPrecision(i + 1); if (precision[i] != p) { fail("column precision " + i + " is " + p + " not " + precision[i]); } } if (scale != null) { int s = meta.getScale(i + 1); if (scale[i] != s) { fail("column scale " + i + " is " + s + " not " + scale[i]); } } } }
From source file:com.glaf.core.jdbc.QueryHelper.java
@SuppressWarnings("unchecked") public List<ColumnDefinition> getColumnDefinitions(String systemName, String sql, Map<String, Object> params) { SqlExecutor sqlExecutor = DBUtils.replaceSQL(sql, params); Connection conn = null;//from ww w .ja va 2 s . co m PreparedStatement psmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { conn = DBConnectionFactory.getConnection(systemName); psmt = conn.prepareStatement(sqlExecutor.getSql()); if (sqlExecutor.getParameter() != null) { List<Object> values = (List<Object>) sqlExecutor.getParameter(); JdbcUtils.fillStatement(psmt, values); } rs = psmt.executeQuery(); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>(); for (int index = 1; index <= count; index++) { int sqlType = rsmd.getColumnType(index); ColumnDefinition column = new ColumnDefinition(); column.setIndex(index); column.setColumnName(rsmd.getColumnName(index)); column.setColumnLabel(rsmd.getColumnLabel(index)); column.setJavaType(FieldType.getJavaType(sqlType)); column.setPrecision(rsmd.getPrecision(index)); column.setScale(rsmd.getScale(index)); if (column.getScale() == 0 && sqlType == Types.NUMERIC) { column.setJavaType("Long"); } column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase())); columns.add(column); } return columns; } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(psmt); JdbcUtils.close(conn); } }
From source file:com.glaf.core.jdbc.QueryHelper.java
@SuppressWarnings("unchecked") public List<ColumnDefinition> getColumns(Connection conn, String sql, Map<String, Object> paramMap) { if (!DBUtils.isLegalQuerySql(sql)) { throw new RuntimeException(" SQL statement illegal "); }// w w w. j a v a 2s. c o m List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>(); PreparedStatement psmt = null; ResultSetMetaData rsmd = null; ResultSet rs = null; try { List<Object> values = null; if (paramMap != null) { SqlExecutor sqlExecutor = DBUtils.replaceSQL(sql, paramMap); sql = sqlExecutor.getSql(); values = (List<Object>) sqlExecutor.getParameter(); } logger.debug("sql:\n" + sql); logger.debug("values:" + values); psmt = conn.prepareStatement(sql); if (values != null && !values.isEmpty()) { JdbcUtils.fillStatement(psmt, values); } rs = psmt.executeQuery(); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); for (int i = 1; i <= count; i++) { int sqlType = rsmd.getColumnType(i); ColumnDefinition column = new ColumnDefinition(); column.setColumnLabel(rsmd.getColumnLabel(i)); column.setColumnName(rsmd.getColumnName(i)); column.setJavaType(FieldType.getJavaType(sqlType)); column.setPrecision(rsmd.getPrecision(i)); column.setScale(rsmd.getScale(i)); column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase())); if (column.getScale() == 0 && sqlType == Types.NUMERIC) { column.setJavaType("Long"); } if (!columns.contains(column)) { columns.add(column); } logger.debug(column.getColumnName() + " sqlType:" + sqlType + " precision:" + column.getPrecision() + " scale:" + column.getScale()); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(psmt); JdbcUtils.close(rs); } return columns; }
From source file:com.glaf.core.jdbc.QueryHelper.java
/** * @param conn//from ww w. j ava2 s. c o m * ? * @param sqlExecutor * * @return */ @SuppressWarnings("unchecked") public List<Map<String, Object>> getResultList(Connection conn, SqlExecutor sqlExecutor) { if (!DBUtils.isLegalQuerySql(sqlExecutor.getSql())) { throw new RuntimeException(" SQL statement illegal "); } List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>(); PreparedStatement psmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { psmt = conn.prepareStatement(sqlExecutor.getSql()); if (sqlExecutor.getParameter() != null) { List<Object> values = (List<Object>) sqlExecutor.getParameter(); JdbcUtils.fillStatement(psmt, values); } rs = psmt.executeQuery(); if (conf.getBoolean("useMyBatisResultHandler", false)) { resultList = this.getResults(rs); } else { rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>(); for (int index = 1; index <= count; index++) { int sqlType = rsmd.getColumnType(index); ColumnDefinition column = new ColumnDefinition(); column.setIndex(index); column.setColumnName(rsmd.getColumnName(index)); column.setColumnLabel(rsmd.getColumnLabel(index)); column.setJavaType(FieldType.getJavaType(sqlType)); column.setPrecision(rsmd.getPrecision(index)); column.setScale(rsmd.getScale(index)); if (column.getScale() == 0 && sqlType == Types.NUMERIC) { column.setJavaType("Long"); } column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase())); columns.add(column); } int startIndex = 1; while (rs.next() && startIndex <= 50000) { int index = 0; startIndex++; Map<String, Object> rowMap = new HashMap<String, Object>(); Iterator<ColumnDefinition> iterator = columns.iterator(); while (iterator.hasNext()) { ColumnDefinition column = iterator.next(); String columnLabel = column.getColumnLabel(); String columnName = column.getColumnName(); if (StringUtils.isEmpty(columnName)) { columnName = column.getColumnLabel(); } columnName = columnName.toLowerCase(); String javaType = column.getJavaType(); index = index + 1; if ("String".equals(javaType)) { String value = rs.getString(column.getIndex()); if (value != null) { value = value.trim(); rowMap.put(columnName, value); rowMap.put(columnLabel, value); } } else if ("Integer".equals(javaType)) { try { Integer value = rs.getInt(column.getIndex()); rowMap.put(columnName, value); rowMap.put(columnLabel, value); } catch (Exception e) { String str = rs.getString(column.getIndex()); logger.error("integer:" + str); str = StringTools.replace(str, "$", ""); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); rowMap.put(columnName, num.intValue()); rowMap.put(columnLabel, rowMap.get(columnName)); logger.debug("?:" + num.intValue()); } } else if ("Long".equals(javaType)) { try { Long value = rs.getLong(column.getIndex()); rowMap.put(columnName, value); rowMap.put(columnLabel, rowMap.get(columnName)); } catch (Exception e) { String str = rs.getString(column.getIndex()); logger.error("long:" + str); str = StringTools.replace(str, "$", ""); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); rowMap.put(columnName, num.longValue()); rowMap.put(columnLabel, num.longValue()); logger.debug("?:" + num.longValue()); } } else if ("Double".equals(javaType)) { try { Double d = rs.getDouble(column.getIndex()); rowMap.put(columnName, d); rowMap.put(columnLabel, d); } catch (Exception e) { String str = rs.getString(column.getIndex()); logger.error("double:" + str); str = StringTools.replace(str, "$", ""); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); rowMap.put(columnName, num.doubleValue()); rowMap.put(columnLabel, num.doubleValue()); logger.debug("?:" + num.doubleValue()); } } else if ("Boolean".equals(javaType)) { rowMap.put(columnName, rs.getBoolean(column.getIndex())); rowMap.put(columnLabel, rowMap.get(columnName)); } else if ("Date".equals(javaType)) { rowMap.put(columnName, rs.getTimestamp(column.getIndex())); rowMap.put(columnLabel, rowMap.get(columnName)); } else if ("Blob".equals(javaType)) { // ignore } else { Object value = rs.getObject(column.getIndex()); if (value != null) { if (value instanceof String) { value = (String) value.toString().trim(); } rowMap.put(columnName, value); rowMap.put(columnLabel, rowMap.get(columnName)); } } } rowMap.put("startIndex", startIndex); resultList.add(rowMap); } } logger.debug(">resultList size=" + resultList.size()); return resultList; } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(psmt); JdbcUtils.close(rs); } }
From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java
/** * Creates an Avro schema from a result set. If the table/record name is known a priori and provided, use that as a * fallback for the record name if it cannot be retrieved from the result set, and finally fall back to a default value. * * @param rs The result set to convert to Avro * @param recordName The a priori record name to use if it cannot be determined from the result set. * @return A Schema object representing the result set converted to an Avro record * @throws SQLException if any error occurs during conversion *//*from w ww . jav a 2s . com*/ public static Schema createSchema(final ResultSet rs, String recordName, boolean convertNames) throws SQLException { final ResultSetMetaData meta = rs.getMetaData(); final int nrOfColumns = meta.getColumnCount(); String tableName = StringUtils.isEmpty(recordName) ? "NiFi_ExecuteSQL_Record" : recordName; if (nrOfColumns > 0) { String tableNameFromMeta = meta.getTableName(1); if (!StringUtils.isBlank(tableNameFromMeta)) { tableName = tableNameFromMeta; } } if (convertNames) { tableName = normalizeNameForAvro(tableName); } final FieldAssembler<Schema> builder = SchemaBuilder.record(tableName).namespace("any.data").fields(); /** * Some missing Avro types - Decimal, Date types. May need some additional work. */ for (int i = 1; i <= nrOfColumns; i++) { /** * as per jdbc 4 specs, getColumnLabel will have the alias for the column, if not it will have the column name. * so it may be a better option to check for columnlabel first and if in case it is null is someimplementation, * check for alias. Postgres is the one that has the null column names for calculated fields. */ String nameOrLabel = StringUtils.isNotEmpty(meta.getColumnLabel(i)) ? meta.getColumnLabel(i) : meta.getColumnName(i); String columnName = convertNames ? normalizeNameForAvro(nameOrLabel) : nameOrLabel; switch (meta.getColumnType(i)) { case CHAR: case LONGNVARCHAR: case LONGVARCHAR: case NCHAR: case NVARCHAR: case VARCHAR: case CLOB: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case BIT: case BOOLEAN: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().booleanType().endUnion() .noDefault(); break; case INTEGER: if (meta.isSigned(i)) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion() .noDefault(); } break; case SMALLINT: case TINYINT: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); break; case BIGINT: // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that. // If the precision > 19 (or is negative), use a string for the type, otherwise use a long. The object(s) will be converted // to strings as necessary int precision = meta.getPrecision(i); if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion() .noDefault(); } break; // java.sql.RowId is interface, is seems to be database // implementation specific, let's convert to String case ROWID: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case FLOAT: case REAL: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().floatType().endUnion() .noDefault(); break; case DOUBLE: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion() .noDefault(); break; // Did not find direct suitable type, need to be clarified!!!! case DECIMAL: case NUMERIC: int scale = meta.getScale(i); if (scale == 0) { if (meta.getPrecision(i) < 10) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType() .endUnion().noDefault(); } } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion() .noDefault(); } break; // Did not find direct suitable type, need to be clarified!!!! case DATE: case TIME: case TIMESTAMP: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case BINARY: case VARBINARY: case LONGVARBINARY: case ARRAY: case BLOB: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().bytesType().endUnion() .noDefault(); break; default: throw new IllegalArgumentException("createSchema: Unknown SQL type " + meta.getColumnType(i) + " cannot be converted to Avro type"); } } return builder.endRecord(); }