List of usage examples for java.sql Types DECIMAL
int DECIMAL
To view the source code for java.sql Types DECIMAL.
Click Source Link
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type DECIMAL
.
From source file:CreateNewType.java
private static Vector getDataTypes(Connection con, String typeToCreate) throws SQLException { String structName = null, distinctName = null, javaName = null; // create a vector of class DataType initialized with // the SQL code, the SQL type name, and two null entries // for the local type name and the creation parameter(s) Vector dataTypes = new Vector(); dataTypes.add(new DataType(java.sql.Types.BIT, "BIT")); dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT")); dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT")); dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER")); dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT")); dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT")); dataTypes.add(new DataType(java.sql.Types.REAL, "REAL")); dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE")); dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC")); dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL")); dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR")); dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR")); dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR")); dataTypes.add(new DataType(java.sql.Types.DATE, "DATE")); dataTypes.add(new DataType(java.sql.Types.TIME, "TIME")); dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP")); dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY")); dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY")); dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY")); dataTypes.add(new DataType(java.sql.Types.NULL, "NULL")); dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER")); dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB")); dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB")); DatabaseMetaData dbmd = con.getMetaData(); ResultSet rs = dbmd.getTypeInfo(); while (rs.next()) { int codeNumber = rs.getInt("DATA_TYPE"); String dbmsName = rs.getString("TYPE_NAME"); String createParams = rs.getString("CREATE_PARAMS"); if (codeNumber == Types.STRUCT && structName == null) structName = dbmsName;//from w w w . ja v a 2s . co m else if (codeNumber == Types.DISTINCT && distinctName == null) distinctName = dbmsName; else if (codeNumber == Types.JAVA_OBJECT && javaName == null) javaName = dbmsName; else { for (int i = 0; i < dataTypes.size(); i++) { // find entry that matches the SQL code, // and if local type and params are not already set, // set them DataType type = (DataType) dataTypes.get(i); if (type.getCode() == codeNumber) { type.setLocalTypeAndParams(dbmsName, createParams); } } } } if (typeToCreate.equals("s")) { int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT }; rs = dbmd.getUDTs(null, "%", "%", types); while (rs.next()) { String typeName = null; DataType dataType = null; if (dbmd.isCatalogAtStart()) typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "." + rs.getString(3); else typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator() + rs.getString(1); switch (rs.getInt(5)) { case Types.STRUCT: dataType = new DataType(Types.STRUCT, typeName); dataType.setLocalTypeAndParams(structName, null); break; case Types.DISTINCT: dataType = new DataType(Types.DISTINCT, typeName); dataType.setLocalTypeAndParams(distinctName, null); break; case Types.JAVA_OBJECT: dataType = new DataType(Types.JAVA_OBJECT, typeName); dataType.setLocalTypeAndParams(javaName, null); break; } dataTypes.add(dataType); } } return dataTypes; }
From source file:com.squid.core.domain.operators.ExtendedType.java
@Override public boolean equals(Object object) { if (this == object) { return true; } else if (object instanceof ExtendedType) { ExtendedType type = (ExtendedType) object; if (type.getDataType() == this.getDataType()) { switch (type.getDataType()) { case Types.DECIMAL: case Types.NUMERIC: return type.getScale() == this.getScale() && type.getSize() == this.getSize(); case Types.NVARCHAR: case Types.VARCHAR: case Types.CHAR: return type.getSize() == this.getSize(); default: return true; }/*from w w w . ja v a2 s . com*/ } else { return false; } } else { return false; } }
From source file:org.executequery.gui.resultset.ResultSetTableModel.java
public void createTable(ResultSet resultSet) { if (!isOpenAndValid(resultSet)) { clearData();//from w w w. java2 s. co m return; } try { resetMetaData(); ResultSetMetaData rsmd = resultSet.getMetaData(); columnHeaders.clear(); visibleColumnHeaders.clear(); tableData.clear(); int zeroBaseIndex = 0; int count = rsmd.getColumnCount(); for (int i = 1; i <= count; i++) { zeroBaseIndex = i - 1; columnHeaders.add(new ResultSetColumnHeader(zeroBaseIndex, rsmd.getColumnLabel(i), rsmd.getColumnName(i), rsmd.getColumnType(i), rsmd.getColumnTypeName(i))); } int recordCount = 0; interrupted = false; if (holdMetaData) { setMetaDataVectors(rsmd); } List<RecordDataItem> rowData; long time = System.currentTimeMillis(); while (resultSet.next()) { if (interrupted || Thread.interrupted()) { throw new InterruptedException(); } recordCount++; rowData = new ArrayList<RecordDataItem>(count); for (int i = 1; i <= count; i++) { zeroBaseIndex = i - 1; ResultSetColumnHeader header = columnHeaders.get(zeroBaseIndex); RecordDataItem value = recordDataItemFactory.create(header); try { int dataType = header.getDataType(); switch (dataType) { // some drivers (informix for example) // was noticed to return the hashcode from // getObject for -1 data types (eg. longvarchar). // force string for these - others stick with // getObject() for default value formatting case Types.CHAR: case Types.VARCHAR: value.setValue(resultSet.getString(i)); break; case Types.DATE: value.setValue(resultSet.getDate(i)); break; case Types.TIME: value.setValue(resultSet.getTime(i)); break; case Types.TIMESTAMP: value.setValue(resultSet.getTimestamp(i)); break; case Types.LONGVARCHAR: case Types.CLOB: value.setValue(resultSet.getClob(i)); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: value.setValue(resultSet.getBytes(i)); break; case Types.BLOB: value.setValue(resultSet.getBlob(i)); break; case Types.BIT: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: case Types.FLOAT: case Types.REAL: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: case Types.NULL: case Types.OTHER: case Types.JAVA_OBJECT: case Types.DISTINCT: case Types.STRUCT: case Types.ARRAY: case Types.REF: case Types.DATALINK: case Types.BOOLEAN: case Types.ROWID: case Types.NCHAR: case Types.NVARCHAR: case Types.LONGNVARCHAR: case Types.NCLOB: case Types.SQLXML: // use getObject for all other known types value.setValue(resultSet.getObject(i)); break; default: // otherwise try as string asStringOrObject(value, resultSet, i); break; } } catch (Exception e) { try { // ... and on dump, resort to string value.setValue(resultSet.getString(i)); } catch (SQLException sqlException) { // catch-all SQLException - yes, this is hideous // noticed with invalid date formatted values in mysql value.setValue("<Error - " + sqlException.getMessage() + ">"); } } if (resultSet.wasNull()) { value.setNull(); } rowData.add(value); } tableData.add(rowData); if (recordCount == maxRecords) { break; } } if (Log.isTraceEnabled()) { Log.trace("Finished populating table model - " + recordCount + " rows - [ " + MiscUtils.formatDuration(System.currentTimeMillis() - time) + "]"); } fireTableStructureChanged(); } catch (SQLException e) { System.err.println("SQL error populating table model at: " + e.getMessage()); Log.debug("Table model error - " + e.getMessage(), e); } catch (Exception e) { if (e instanceof InterruptedException) { Log.debug("ResultSet generation interrupted.", e); } else { String message = e.getMessage(); if (StringUtils.isBlank(message)) { System.err.println("Exception populating table model."); } else { System.err.println("Exception populating table model at: " + message); } Log.debug("Table model error - ", e); } } finally { if (resultSet != null) { try { resultSet.close(); Statement statement = resultSet.getStatement(); if (statement != null) { statement.close(); } } catch (SQLException e) { } } } }
From source file:org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplateTests.java
public void testUpdateWithTypedParameters() throws SQLException { mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.setObject(2, new Integer(1), Types.INTEGER); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.executeUpdate(); ctrlPreparedStatement.setReturnValue(1); if (debugEnabled) { mockPreparedStatement.getWarnings(); ctrlPreparedStatement.setReturnValue(null); }//from w w w . j av a 2 s. c o m mockPreparedStatement.close(); ctrlPreparedStatement.setVoidCallable(); mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); ctrlConnection.setReturnValue(mockPreparedStatement); replay(); NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource); Map params = new HashMap(); params.put("perfId", new SqlParameterValue(Types.DECIMAL, new Integer(1))); params.put("priceId", new SqlParameterValue(Types.INTEGER, new Integer(1))); int rowsAffected = jt.update(UPDATE_NAMED_PARAMETERS, params); assertEquals(1, rowsAffected); }
From source file:it.alidays.mapengine.codegenerator.MapperEngineCodeGenerator.java
private static void createMapClass(Retrieve retrieve, Map<String, Integer> columns, String packageName, File destinationDir)/* ww w.ja v a 2 s. c o m*/ throws JClassAlreadyExistsException, MapperEngineCodeGeneratorException, IOException { JCodeModel codeModel = new JCodeModel(); JDefinedClass mapClass = codeModel._class(String.format("%s.%sMap", packageName, retrieve.getId())); mapClass.javadoc().append("Auto generated class. Do not modify!"); // Constructor JMethod constructor = mapClass.constructor(JMod.PROTECTED); constructor.param(codeModel.ref(Map.class).narrow(String.class, Object.class), "data"); for (String column : columns.keySet()) { String varName = WordUtils.uncapitalize(column); Class<?> type = null; switch (columns.get(column)) { case Types.INTEGER: type = Integer.class; break; case Types.VARCHAR: type = String.class; break; case Types.DECIMAL: type = BigDecimal.class; break; default: throw new MapperEngineCodeGeneratorException( String.format("Missing Type map for column %s: %d", column, columns.get(column))); } JFieldVar field = mapClass.field(JMod.PRIVATE | JMod.FINAL, type, varName); // Getter JMethod getter = mapClass.method(JMod.PUBLIC, type, String.format("get%s", column)); getter.body()._return(JExpr._this().ref(field)); constructor.body().assign(JExpr._this().ref(varName), JExpr.cast(codeModel.ref(type), JExpr.ref("data").invoke("get").arg(column))); } codeModel.build(destinationDir); }
From source file:org.apache.ddlutils.platform.interbase.InterbaseModelReader.java
/** * Adjusts the columns in the table by fixing types and default values. * /*ww w . j a va2 s .com*/ * @param table The table */ protected void adjustColumns(Table table) { Column[] columns = table.getColumns(); for (int idx = 0; idx < columns.length; idx++) { if (columns[idx].getTypeCode() == Types.FLOAT) { columns[idx].setTypeCode(Types.REAL); } else if ((columns[idx].getTypeCode() == Types.NUMERIC) || (columns[idx].getTypeCode() == Types.DECIMAL)) { if ((columns[idx].getTypeCode() == Types.NUMERIC) && (columns[idx].getSizeAsInt() == 18) && (columns[idx].getScale() == 0)) { columns[idx].setTypeCode(Types.BIGINT); } } else if (TypeMap.isTextType(columns[idx].getTypeCode())) { columns[idx].setDefaultValue(unescape(columns[idx].getDefaultValue(), "'", "''")); } } }
From source file:com.streamsets.pipeline.stage.it.DecimalTypeIT.java
@Test public void zeroScale() throws Exception { executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(2, 0)) PARTITIONED BY (dt string) STORED AS AVRO"); HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(2, 0).build(); HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build(); List<Record> records = new LinkedList<>(); Map<String, Field> map = new LinkedHashMap<>(); map.put("id", Field.create(Field.Type.INTEGER, 1)); map.put("dec", Field.create(BigDecimal.valueOf(12))); Record record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); records.add(record);//from w w w .j av a 2s. c o m processRecords(processor, hiveTarget, records); assertQueryResult("select * from tbl order by id", new QueryValidator() { @Override public void validateResultSet(ResultSet rs) throws Exception { assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER), new ImmutablePair("tbl.dec", Types.DECIMAL), new ImmutablePair("tbl.dt", Types.VARCHAR)); Assert.assertTrue("Table tbl doesn't contain any rows", rs.next()); Assert.assertEquals(1, rs.getLong(1)); Assert.assertEquals(BigDecimal.valueOf(12), rs.getBigDecimal(2)); Assert.assertFalse("Unexpected number of rows", rs.next()); } }); }
From source file:com.flexive.core.storage.GenericDivisionExporter.java
/** * Dump a generic table to XML/*w w w.j a v a 2 s. c o m*/ * * @param tableName name of the table * @param stmt an open statement * @param out output stream * @param sb an available and valid StringBuilder * @param xmlTag name of the xml tag to write per row * @param idColumn (optional) id column to sort results * @param onlyBinaries process binary fields (else these will be ignored) * @throws SQLException on errors * @throws IOException on errors */ private void dumpTable(String tableName, Statement stmt, OutputStream out, StringBuilder sb, String xmlTag, String idColumn, boolean onlyBinaries) throws SQLException, IOException { ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName + (StringUtils.isEmpty(idColumn) ? "" : " ORDER BY " + idColumn + " ASC")); final ResultSetMetaData md = rs.getMetaData(); String value, att; boolean hasSubTags; while (rs.next()) { hasSubTags = false; if (!onlyBinaries) { sb.setLength(0); sb.append(" <").append(xmlTag); } for (int i = 1; i <= md.getColumnCount(); i++) { value = null; att = md.getColumnName(i).toLowerCase(); switch (md.getColumnType(i)) { case java.sql.Types.DECIMAL: case java.sql.Types.NUMERIC: case java.sql.Types.BIGINT: if (!onlyBinaries) { value = String.valueOf(rs.getBigDecimal(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: if (!onlyBinaries) { value = String.valueOf(rs.getLong(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: if (!onlyBinaries) { value = String.valueOf(rs.getDouble(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: if (!onlyBinaries) { final Timestamp ts = rs.getTimestamp(i); if (rs.wasNull()) value = null; else value = FxFormatUtils.getDateTimeFormat().format(ts); } break; case java.sql.Types.BIT: case java.sql.Types.CHAR: case java.sql.Types.BOOLEAN: if (!onlyBinaries) { value = rs.getBoolean(i) ? "1" : "0"; if (rs.wasNull()) value = null; } break; case java.sql.Types.CLOB: case java.sql.Types.BLOB: case java.sql.Types.LONGVARBINARY: case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARBINARY: case java.sql.Types.VARCHAR: case java.sql.Types.BINARY: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: hasSubTags = true; break; default: LOG.warn("Unhandled type [" + md.getColumnType(i) + "] for [" + tableName + "." + att + "]"); } if (value != null && !onlyBinaries) sb.append(' ').append(att).append("=\"").append(value).append("\""); } if (hasSubTags) { if (!onlyBinaries) sb.append(">\n"); for (int i = 1; i <= md.getColumnCount(); i++) { switch (md.getColumnType(i)) { case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: case java.sql.Types.BLOB: case java.sql.Types.BINARY: if (idColumn == null) throw new IllegalArgumentException("Id column required to process binaries!"); String binFile = FOLDER_BINARY + "/BIN_" + String.valueOf(rs.getLong(idColumn)) + "_" + i + ".blob"; att = md.getColumnName(i).toLowerCase(); if (onlyBinaries) { if (!(out instanceof ZipOutputStream)) throw new IllegalArgumentException( "out has to be a ZipOutputStream to store binaries!"); ZipOutputStream zip = (ZipOutputStream) out; InputStream in = rs.getBinaryStream(i); if (rs.wasNull()) break; ZipEntry ze = new ZipEntry(binFile); zip.putNextEntry(ze); byte[] buffer = new byte[4096]; int read; while ((read = in.read(buffer)) != -1) zip.write(buffer, 0, read); in.close(); zip.closeEntry(); zip.flush(); } else { InputStream in = rs.getBinaryStream(i); //need to fetch to see if it is empty if (rs.wasNull()) break; in.close(); sb.append(" <").append(att).append(">").append(binFile).append("</").append(att) .append(">\n"); } break; case java.sql.Types.CLOB: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARCHAR: if (!onlyBinaries) { value = rs.getString(i); if (rs.wasNull()) break; att = md.getColumnName(i).toLowerCase(); sb.append(" <").append(att).append('>'); escape(sb, value); sb.append("</").append(att).append(">\n"); } break; } } if (!onlyBinaries) sb.append(" </").append(xmlTag).append(">\n"); } else { if (!onlyBinaries) sb.append("/>\n"); } if (!onlyBinaries) write(out, sb); } }
From source file:org.castor.jdo.engine.SQLTypeInfos.java
/** * Get value from given ResultSet at given index with given SQL type. * // w w w .j av a2 s . co m * @param rs The ResultSet to get the value from. * @param index The index of the value in the ResultSet. * @param sqlType The SQL type of the value. * @return The value. * @throws SQLException If a database access error occurs. */ public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException { switch (sqlType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return rs.getString(index); case Types.DECIMAL: case Types.NUMERIC: return rs.getBigDecimal(index); case Types.INTEGER: int intVal = rs.getInt(index); return (rs.wasNull() ? null : new Integer(intVal)); case Types.TIME: return rs.getTime(index, getCalendar()); case Types.DATE: return rs.getDate(index); case Types.TIMESTAMP: return rs.getTimestamp(index, getCalendar()); case Types.FLOAT: case Types.DOUBLE: double doubleVal = rs.getDouble(index); return (rs.wasNull() ? null : new Double(doubleVal)); case Types.REAL: float floatVal = rs.getFloat(index); return (rs.wasNull() ? null : new Float(floatVal)); case Types.SMALLINT: short shortVal = rs.getShort(index); return (rs.wasNull() ? null : new Short(shortVal)); case Types.TINYINT: byte byteVal = rs.getByte(index); return (rs.wasNull() ? null : new Byte(byteVal)); case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: return rs.getBytes(index); case Types.BLOB: Blob blob = rs.getBlob(index); return (blob == null ? null : blob.getBinaryStream()); case Types.CLOB: return rs.getClob(index); case Types.BIGINT: long longVal = rs.getLong(index); return (rs.wasNull() ? null : new Long(longVal)); case Types.BIT: boolean boolVal = rs.getBoolean(index); return (rs.wasNull() ? null : new Boolean(boolVal)); default: Object value = rs.getObject(index); return (rs.wasNull() ? null : value); } }
From source file:org.apache.cayenne.migration.MigrationGenerator.java
protected String nameForJdbcType(int type) { switch (type) { case Types.ARRAY: return "array"; case Types.BIGINT: return "bigInt"; case Types.BINARY: return "binary"; case Types.BIT: return "bit"; case Types.BLOB: return "blob"; case Types.BOOLEAN: return "boolean"; case Types.CHAR: return "char"; case Types.CLOB: return "clob"; case Types.DATE: return "date"; case Types.DECIMAL: return "decimal"; case Types.DOUBLE: return "double"; case Types.FLOAT: return "float"; case Types.INTEGER: return "integer"; case Types.LONGVARBINARY: return "longVarBinary"; case Types.LONGVARCHAR: return "longVarChar"; case Types.NUMERIC: return "numeric"; case Types.REAL: return "real"; case Types.SMALLINT: return "smallInt"; case Types.TIME: return "time"; case Types.TIMESTAMP: return "timestamp"; case Types.TINYINT: return "tinyInt"; case Types.VARBINARY: return "varBinary"; case Types.VARCHAR: return "varchar"; default://from www .j av a 2 s .c om return null; } }