List of usage examples for java.sql Types NUMERIC
int NUMERIC
To view the source code for java.sql Types NUMERIC.
Click Source Link
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type NUMERIC
.
From source file:org.seasar.dbflute.logic.replaceschema.loaddata.impl.DfAbsractDataWriter.java
/** * Get the bind type to find a value type. * @param tableName The name of table corresponding to column. (NotNull) * @param columnMeta The meta info of column. (NotNull) * @return The type of column. (NullAllowed: However Basically NotNull) *//*from ww w .ja v a2 s . c o m*/ protected Class<?> getBindType(String tableName, DfColumnMeta columnMeta) { Map<String, Class<?>> cacheMap = _bindTypeCacheMap.get(tableName); if (cacheMap == null) { cacheMap = StringKeyMap.createAsFlexibleOrdered(); _bindTypeCacheMap.put(tableName, cacheMap); } final String columnName = columnMeta.getColumnName(); Class<?> bindType = cacheMap.get(columnName); if (bindType != null) { // cache hit return bindType; } // use mapped JDBC defined value if found (basically found) // because it has already been resolved about JDBC specification per DBMS final String jdbcType = _columnHandler.getColumnJdbcType(columnMeta); Integer jdbcDefValue = TypeMap.getJdbcDefValueByJdbcType(jdbcType); if (jdbcDefValue == null) { // basically no way jdbcDefValue = columnMeta.getJdbcDefValue(); // as plain } // ReplaceSchema uses an own original mapping way // (not uses Generate mapping) // it's simple mapping (for string processor) if (jdbcDefValue == Types.CHAR || jdbcDefValue == Types.VARCHAR || jdbcDefValue == Types.LONGVARCHAR || jdbcDefValue == Types.CLOB) { bindType = String.class; } else if (jdbcDefValue == Types.TINYINT || jdbcDefValue == Types.SMALLINT || jdbcDefValue == Types.INTEGER) { bindType = Integer.class; } else if (jdbcDefValue == Types.BIGINT) { bindType = Long.class; } else if (jdbcDefValue == Types.DECIMAL || jdbcDefValue == Types.NUMERIC) { bindType = BigDecimal.class; } else if (jdbcDefValue == Types.TIMESTAMP) { bindType = Timestamp.class; } else if (jdbcDefValue == Types.TIME) { bindType = Time.class; } else if (jdbcDefValue == Types.DATE) { // it depends on value type settings // that which is bound java.sql.Date or java.sql.Timestamp bindType = java.util.Date.class; } else if (jdbcDefValue == Types.BIT || jdbcDefValue == Types.BOOLEAN) { bindType = Boolean.class; } else if (jdbcDefValue == Types.BINARY || jdbcDefValue == Types.VARBINARY || jdbcDefValue == Types.LONGVARBINARY || jdbcDefValue == Types.BLOB) { bindType = byte[].class; } else if (jdbcDefValue == Types.OTHER && TypeMap.UUID.equalsIgnoreCase(jdbcType)) { // [UUID Headache]: The reason why UUID type has not been supported yet on JDBC. bindType = UUID.class; } else { bindType = Object.class; } cacheMap.put(columnName, bindType); return bindType; }
From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatUtilities.java
/** * Resolve a database-specific type to HCat data type. Largely follows Sqoop's * hive translation./*from w w w . ja va 2 s . c om*/ * @param sqlType * sql type * @return hcat type */ public static String toHCatType(int sqlType) { switch (sqlType) { // Ideally TINYINT and SMALLINT should be mapped to their // HCat equivalents tinyint and smallint respectively // But the Sqoop Java type conversion has them mapped to Integer // Even though the referenced Java doc clearly recommends otherwise. // Changing this now can cause many of the sequence file usages to // break as value class implementations will change. So, we // just use the same behavior here. case Types.SMALLINT: case Types.TINYINT: case Types.INTEGER: return "int"; case Types.VARCHAR: return "varchar"; case Types.CHAR: return "char"; case Types.LONGVARCHAR: case Types.NVARCHAR: case Types.NCHAR: case Types.LONGNVARCHAR: case Types.DATE: case Types.TIME: case Types.TIMESTAMP: case Types.CLOB: return "string"; case Types.FLOAT: case Types.REAL: return "float"; case Types.NUMERIC: case Types.DECIMAL: return "decimal"; case Types.DOUBLE: return "double"; case Types.BIT: case Types.BOOLEAN: return "boolean"; case Types.BIGINT: return "bigint"; case Types.BINARY: case Types.VARBINARY: case Types.BLOB: case Types.LONGVARBINARY: return "binary"; default: throw new IllegalArgumentException("Cannot convert SQL type to HCatalog type " + sqlType); } }
From source file:org.jumpmind.symmetric.db.AbstractTriggerTemplate.java
protected String buildKeyVariablesDeclare(Column[] columns, String prefix) { String text = ""; for (int i = 0; i < columns.length; i++) { text += "declare @" + prefix + "pk" + i + " "; switch (columns[i].getMappedTypeCode()) { case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: text += "bigint\n"; break; case Types.NUMERIC: case Types.DECIMAL: text += "decimal\n"; break; case Types.FLOAT: case Types.REAL: case Types.DOUBLE: text += "float\n"; break; case Types.CHAR: case Types.VARCHAR: case ColumnTypes.NVARCHAR: case ColumnTypes.LONGNVARCHAR: case Types.LONGVARCHAR: text += "varchar(1000)\n"; break; case Types.DATE: text += "date\n"; break; case Types.TIME: text += "time\n"; break; case Types.TIMESTAMP: text += "datetime\n"; break; case Types.BOOLEAN: case Types.BIT: text += "bit\n"; break; case Types.CLOB: text += "varchar(max)\n"; break; case Types.BLOB: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case -10: // SQL-Server ntext binary type text += "varbinary(max)\n"; break; case Types.OTHER: text += "varbinary(max)\n"; break; default:/* w ww . ja v a 2 s . c o m*/ if (columns[i].getJdbcTypeName() != null && columns[i].getJdbcTypeName().equalsIgnoreCase("interval")) { text += "interval"; break; } throw new NotImplementedException(columns[i] + " is of type " + columns[i].getMappedType()); } } return text; }
From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
/** * This method reads table column meta data. * * @param tableName Name of the table/* w w w . j a v a 2s . co m*/ * @return table MetaData * @throws ODataServiceFault */ private Map<String, DataColumn> readTableColumnMetaData(String tableName, DatabaseMetaData meta) throws ODataServiceFault { ResultSet resultSet = null; Map<String, DataColumn> columnMap = new HashMap<>(); try { resultSet = meta.getColumns(null, null, tableName, null); int i = 1; while (resultSet.next()) { String columnName = resultSet.getString("COLUMN_NAME"); int columnType = resultSet.getInt("DATA_TYPE"); int size = resultSet.getInt("COLUMN_SIZE"); boolean nullable = resultSet.getBoolean("NULLABLE"); String columnDefaultVal = resultSet.getString("COLUMN_DEF"); int precision = resultSet.getMetaData().getPrecision(i); int scale = resultSet.getMetaData().getScale(i); DataColumn column = new DataColumn(columnName, getODataDataType(columnType), i, nullable, size); if (null != columnDefaultVal) { column.setDefaultValue(columnDefaultVal); } if (Types.DOUBLE == columnType || Types.FLOAT == columnType || Types.DECIMAL == columnType || Types.NUMERIC == columnType || Types.REAL == columnType) { column.setPrecision(precision); if (scale == 0) { //setting default scale as 5 column.setScale(precision); } else { column.setScale(scale); } } columnMap.put(columnName, column); addDataType(tableName, columnName, columnType); i++; } return columnMap; } catch (SQLException e) { throw new ODataServiceFault(e, "Error in reading table meta data in " + tableName + " table. :" + e.getMessage()); } finally { releaseResources(resultSet, null); } }
From source file:org.apache.ddlutils.TestAgainstLiveDatabaseBase.java
/** * Asserts that the two given columns are equal. * //from ww w. j av a2s . c o m * @param expected The expected column * @param actual The actual column * @param caseSensitive Whether case matters when comparing */ protected void assertEquals(Column expected, Column actual, boolean caseSensitive) { if (caseSensitive) { assertEquals("Column names do not match.", getPlatform().getSqlBuilder().shortenName(expected.getName(), getSqlBuilder().getMaxColumnNameLength()), getPlatform().getSqlBuilder().shortenName(actual.getName(), getSqlBuilder().getMaxColumnNameLength())); } else { assertEquals("Column names do not match (ignoring case).", getPlatform().getSqlBuilder().shortenName(expected.getName().toUpperCase(), getSqlBuilder().getMaxColumnNameLength()), getPlatform().getSqlBuilder().shortenName(actual.getName().toUpperCase(), getSqlBuilder().getMaxColumnNameLength())); } assertEquals("Primary key status not the same for column " + actual.getName() + ".", expected.isPrimaryKey(), actual.isPrimaryKey()); assertEquals("Required status not the same for column " + actual.getName() + ".", expected.isRequired(), actual.isRequired()); if (getPlatformInfo().getIdentityStatusReadingSupported()) { // we're only comparing this if the platform can actually read the // auto-increment status back from an existing database assertEquals("Auto-increment status not the same for column " + actual.getName() + ".", expected.isAutoIncrement(), actual.isAutoIncrement()); } assertEquals("Type not the same for column " + actual.getName() + ".", expected.getType(), actual.getType()); assertEquals("Type code not the same for column " + actual.getName() + ".", expected.getTypeCode(), actual.getTypeCode()); assertEquals("Parsed default values do not match for column " + actual.getName() + ".", expected.getParsedDefaultValue(), actual.getParsedDefaultValue()); // comparing the size makes only sense for types where it is relevant if ((expected.getTypeCode() == Types.NUMERIC) || (expected.getTypeCode() == Types.DECIMAL)) { assertEquals("Precision not the same for column " + actual.getName() + ".", expected.getSizeAsInt(), actual.getSizeAsInt()); assertEquals("Scale not the same for column " + actual.getName() + ".", expected.getScale(), actual.getScale()); } else if ((expected.getTypeCode() == Types.CHAR) || (expected.getTypeCode() == Types.VARCHAR) || (expected.getTypeCode() == Types.BINARY) || (expected.getTypeCode() == Types.VARBINARY)) { assertEquals("Size not the same for column " + actual.getName() + ".", expected.getSize(), actual.getSize()); } }
From source file:org.springframework.jdbc.object.SqlQueryTests.java
public void testNamedParameterUsingInvalidQuestionMarkPlaceHolders() throws SQLException { mockConnection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID_REUSED_1, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ctrlConnection.setReturnValue(mockPreparedStatement); replay();// w w w. j a v a2 s . com class CustomerQuery extends MappingSqlQuery { public CustomerQuery(DataSource ds) { super(ds, SELECT_ID_FORENAME_WHERE_ID_REUSED_1); setResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); declareParameter(new SqlParameter("id1", Types.NUMERIC)); compile(); } protected Object mapRow(ResultSet rs, int rownum) throws SQLException { Customer cust = new Customer(); cust.setId(rs.getInt(COLUMN_NAMES[0])); cust.setForename(rs.getString(COLUMN_NAMES[1])); return cust; } public List findCustomers(Integer id1) { Map params = new HashMap(); params.put("id1", id1); return (List) executeByNamedParam(params); } } CustomerQuery query = new CustomerQuery(mockDataSource); try { List cust = query.findCustomers(new Integer(1)); fail("Should have caused an InvalidDataAccessApiUsageException"); } catch (InvalidDataAccessApiUsageException e) { } }
From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java
private void setPreparedStatmentForCurrentColumn(PreparedStatement ps, int index, CSVColumnState column, ProfileRecipientFields bean, ImportProfile importProfile, ValidatorResults validatorResults) throws SQLException { String value = Toolkit.getValueFromBean(bean, column.getColName()); if (column.getType() == CSVColumnState.TYPE_NUMERIC && column.getColName().equals("gender")) { if (StringUtils.isEmpty(value) || value == null) { ps.setInt(index, 2);// w ww. j av a2 s . c o m } else { if (GenericValidator.isInt(value) && Integer.valueOf(value) <= 5 && Integer.valueOf(value) >= 0) { ps.setInt(index, Integer.valueOf(value)); } else { final Integer intValue = importProfile.getGenderMapping().get(value); ps.setInt(index, intValue); } } } else if (column.getType() == CSVColumnState.TYPE_CHAR) { if (value == null) { ps.setNull(index, Types.VARCHAR); } else { String columnName = column.getColName(); if (columnName.equals("email")) { value = value.toLowerCase(); if (validatorResults != null && !ImportUtils.checkIsCurrentFieldValid(validatorResults, "email", "checkRange")) { throw new ImportRecipientsToolongValueException(value); } } else if (importProfile.getKeyColumns().contains(columnName) || (importProfile.getKeyColumns().isEmpty() && columnName.equals(importProfile.getKeyColumn()))) { // range validation for keyColumn if (validatorResults != null && !ImportUtils.checkIsCurrentFieldValid(validatorResults, columnName, "checkRange")) { throw new ImportRecipientsToolongValueException(value); } } if (AgnUtils.isOracleDB()) { ps.setString(index, value); } else if (AgnUtils.isMySQLDB()) { if (column.isNullable() && value.isEmpty()) { ps.setNull(index, Types.VARCHAR); } else { ps.setString(index, value); } } } } else if (column.getType() == CSVColumnState.TYPE_NUMERIC) { if (StringUtils.isEmpty(value) || value == null) { ps.setNull(index, Types.NUMERIC); } else { ps.setDouble(index, Double.valueOf(value)); } } else if (column.getType() == CSVColumnState.TYPE_DATE) { if (StringUtils.isEmpty(value) || value == null) { ps.setNull(index, Types.DATE); } else { Date date = ImportUtils.getDateAsString(value, importProfile.getDateFormat()); ps.setTimestamp(index, new Timestamp(date.getTime())); } } }
From source file:com.mirth.connect.donkey.test.util.TestUtils.java
private static String typeToString(int sqlType) { switch (sqlType) { 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.DATALINK: return "DATALINK"; case Types.DATE: return "DATE"; case Types.DECIMAL: return "DECIMAL"; case Types.DISTINCT: return "DISTINCT"; case Types.DOUBLE: return "DOUBLE"; case Types.FLOAT: return "FLOAT"; case Types.INTEGER: return "INTEGER"; case Types.JAVA_OBJECT: return "JAVA_OBJECT"; case Types.LONGNVARCHAR: return "LONGNVARCHAR"; case Types.LONGVARBINARY: return "LONGVARBINARY"; case Types.LONGVARCHAR: return "LONGVARCHAR"; case Types.NCHAR: return "NCHAR"; case Types.NCLOB: return "NCLOB"; case Types.NULL: return "NULL"; case Types.NUMERIC: return "NUMERIC"; case Types.NVARCHAR: return "NVARCHAR"; case Types.OTHER: return "OTHER"; case Types.REAL: return "REAL"; case Types.REF: return "REF"; case Types.ROWID: return "ROWID"; case Types.SMALLINT: return "SMALLINT"; case Types.SQLXML: return "SQLXML"; case Types.STRUCT: return "STRUCT"; 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:// ww w . j a va 2 s .co m return "UNKNOWN"; } }
From source file:org.springframework.jdbc.object.SqlQueryTests.java
public void testUpdateCustomers() throws SQLException { mockResultSet.next();/*from w w w . j a v a2 s .co m*/ ctrlResultSet.setReturnValue(true); mockResultSet.getInt("id"); ctrlResultSet.setReturnValue(1); mockResultSet.updateString(2, "Rod"); ctrlResultSet.setVoidCallable(); mockResultSet.updateRow(); ctrlResultSet.setVoidCallable(); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getInt("id"); ctrlResultSet.setReturnValue(2); mockResultSet.updateString(2, "Thomas"); ctrlResultSet.setVoidCallable(); mockResultSet.updateRow(); ctrlResultSet.setVoidCallable(); mockResultSet.next(); ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); mockPreparedStatement.setObject(1, new Integer(2), Types.NUMERIC); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.executeQuery(); ctrlPreparedStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockPreparedStatement.getWarnings(); ctrlPreparedStatement.setReturnValue(null); } mockPreparedStatement.close(); ctrlPreparedStatement.setVoidCallable(); mockConnection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); ctrlConnection.setReturnValue(mockPreparedStatement); replay(); class CustomerUpdateQuery extends UpdatableSqlQuery { public CustomerUpdateQuery(DataSource ds) { super(ds, SELECT_ID_FORENAME_WHERE_ID); declareParameter(new SqlParameter(Types.NUMERIC)); compile(); } protected Object updateRow(ResultSet rs, int rownum, Map context) throws SQLException { rs.updateString(2, "" + context.get(new Integer(rs.getInt(COLUMN_NAMES[0])))); return null; } } CustomerUpdateQuery query = new CustomerUpdateQuery(mockDataSource); Map values = new HashMap(2); values.put(new Integer(1), "Rod"); values.put(new Integer(2), "Thomas"); List customers = query.execute(2, values); }
From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java
/** * {@inheritDoc}//w ww .ja v a 2 s . c om */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public long createGroup(long typeId, FxGroupEdit group, String parentXPath, String assignmentAlias) throws FxApplicationException { FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.StructureManagement); Connection con = null; PreparedStatement ps = null; StringBuilder sql = new StringBuilder(2000); long newGroupId; long newAssignmentId; try { parentXPath = parentXPath.toUpperCase(); assignmentAlias = assignmentAlias.toUpperCase(); FxType type = CacheAdmin.getEnvironment().getType(typeId); FxAssignment tmp = type.getAssignment(parentXPath); if (tmp != null && tmp instanceof FxPropertyAssignment) throw new FxInvalidParameterException("ex.structure.assignment.noGroup", parentXPath); //parentXPath is valid, create the group, then assign it to root newGroupId = seq.getId(FxSystemSequencer.TYPEGROUP); con = Database.getDbConnection(); ContentStorage storage = StorageManager.getContentStorage(type.getStorageMode()); // do not allow to add mandatory groups (i.e. min multiplicity > 0) to types for which content exists if (storage.getTypeInstanceCount(con, typeId) > 0 && group.getMultiplicity().getMin() > 0) { throw new FxCreateException("ex.structure.group.creation.exisitingContentMultiplicityError", group.getName(), group.getMultiplicity().getMin()); } //create group sql.append("INSERT INTO ").append(TBL_STRUCT_GROUPS) .append("(ID,NAME,DEFMINMULT,DEFMAXMULT,MAYOVERRIDEMULT)VALUES(?,?,?,?,?)"); ps = con.prepareStatement(sql.toString()); ps.setLong(1, newGroupId); ps.setString(2, group.getName()); ps.setInt(3, group.getMultiplicity().getMin()); ps.setInt(4, group.getMultiplicity().getMax()); ps.setBoolean(5, group.mayOverrideBaseMultiplicity()); ps.executeUpdate(); ps.close(); sql.setLength(0); Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con, TBL_STRUCT_GROUPS, new String[] { "DESCRIPTION", "HINT" }, "ID", newGroupId); //calc new position sql.append("SELECT COALESCE(MAX(POS)+1,0) FROM ").append(TBL_STRUCT_ASSIGNMENTS) .append(" WHERE PARENTGROUP=? AND TYPEDEF=?"); ps = con.prepareStatement(sql.toString()); ps.setLong(1, (tmp == null ? FxAssignment.NO_PARENT : tmp.getId())); ps.setLong(2, typeId); ResultSet rs = ps.executeQuery(); long pos = 0; if (rs != null && rs.next()) pos = rs.getLong(1); ps.close(); storeOptions(con, TBL_STRUCT_GROUP_OPTIONS, "ID", newGroupId, null, group.getOptions()); sql.setLength(0); //create root assignment sql.append("INSERT INTO ").append(TBL_STRUCT_ASSIGNMENTS). // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 append("(ID,ATYPE,ENABLED,TYPEDEF,MINMULT,MAXMULT,DEFMULT,POS,XPATH,XALIAS,BASE,PARENTGROUP,AGROUP,GROUPMODE)" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); ps = con.prepareStatement(sql.toString()); newAssignmentId = seq.getId(FxSystemSequencer.ASSIGNMENT); ps.setLong(1, newAssignmentId); ps.setInt(2, FxAssignment.TYPE_GROUP); ps.setBoolean(3, true); ps.setLong(4, typeId); ps.setInt(5, group.getMultiplicity().getMin()); ps.setInt(6, group.getMultiplicity().getMax()); if (group.getMultiplicity().isValid(group.getAssignmentDefaultMultiplicity())) { ps.setInt(7, group.getAssignmentDefaultMultiplicity()); } else { //default is min(min,1). ps.setInt(7, group.getMultiplicity().getMin() > 1 ? group.getMultiplicity().getMin() : 1); } ps.setLong(8, pos); if (parentXPath == null || "/".equals(parentXPath)) parentXPath = ""; ps.setString(9, type.getName() + XPathElement.stripType(parentXPath) + "/" + assignmentAlias); ps.setString(10, assignmentAlias); ps.setNull(11, java.sql.Types.NUMERIC); ps.setLong(12, (tmp == null ? FxAssignment.NO_PARENT : tmp.getId())); ps.setLong(13, newGroupId); ps.setInt(14, group.getAssignmentGroupMode().getId()); ps.executeUpdate(); Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con, TBL_STRUCT_ASSIGNMENTS, new String[] { "DESCRIPTION", "HINT" }, "ID", newAssignmentId); StructureLoader.reloadAssignments(FxContext.get().getDivisionId()); htracker.track(type, "history.assignment.createGroup", group.getName(), type.getId(), type.getName()); if (type.getId() != FxType.ROOT_ID) createInheritedAssignments(CacheAdmin.getEnvironment().getAssignment(newAssignmentId), con, sql, type.getDerivedTypes()); } catch (FxNotFoundException e) { EJBUtils.rollback(ctx); throw new FxCreateException(e); } catch (FxLoadException e) { EJBUtils.rollback(ctx); throw new FxCreateException(e); } catch (SQLException e) { final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e); EJBUtils.rollback(ctx); if (uniqueConstraintViolation) throw new FxEntryExistsException("ex.structure.group.exists", group.getName(), (parentXPath.length() == 0 ? "/" : parentXPath)); throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { Database.closeObjects(AssignmentEngineBean.class, con, ps); } return newAssignmentId; }