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:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java
/** * Create a new main entry/* w ww. j a v a2 s . c o m*/ * * @param con an open and valid connection * @param newId the id to use * @param version the version to use * @param content content to create * @return primary key of the created content * @throws FxCreateException on errors */ protected FxPK createMainEntry(Connection con, long newId, int version, FxContent content, boolean keepCreationLCI) throws FxCreateException { PreparedStatement ps = null; FxPK pk = new FxPK(newId, version); try { ps = con.prepareStatement(CONTENT_MAIN_INSERT); ps.setLong(1, newId); ps.setInt(2, version); ps.setLong(3, content.getTypeId()); ps.setLong(4, content.getAclIds().size() > 1 ? ACL.NULL_ACL_ID : content.getAclIds().get(0)); ps.setLong(5, content.getStepId()); ps.setInt(6, 1); //if creating a new version, max_ver will be fixed in a later step ps.setInt(7, content.isLiveVersion() ? 1 : 0); ps.setBoolean(8, content.isMaxVersion()); ps.setBoolean(9, content.isLiveVersion()); ps.setBoolean(10, content.isActive()); ps.setInt(11, (int) content.getMainLanguage()); if (content.isRelation()) { ps.setLong(12, content.getRelatedSource().getId()); ps.setInt(13, content.getRelatedSource().getVersion()); ps.setLong(14, content.getRelatedDestination().getId()); ps.setInt(15, content.getRelatedDestination().getVersion()); ps.setLong(16, content.getRelatedSourcePosition()); ps.setLong(17, content.getRelatedDestinationPosition()); } else { ps.setNull(12, java.sql.Types.NUMERIC); ps.setNull(13, java.sql.Types.NUMERIC); ps.setNull(14, java.sql.Types.NUMERIC); ps.setNull(15, java.sql.Types.NUMERIC); ps.setNull(16, java.sql.Types.NUMERIC); ps.setNull(17, java.sql.Types.NUMERIC); } if (!content.isForceLifeCycle()) { final long userId = FxContext.getUserTicket().getUserId(); final long now = System.currentTimeMillis(); if (keepCreationLCI) { // keep created_at of existing content ps.setLong(18, content.getValue(FxLargeNumber.class, "/CREATED_BY").getBestTranslation()); ps.setLong(19, content.getValue(FxDateTime.class, "/CREATED_AT").getBestTranslation().getTime()); } else { ps.setLong(18, userId); ps.setLong(19, now); } ps.setLong(20, userId); ps.setLong(21, now); } else { ps.setLong(18, content.getValue(FxLargeNumber.class, "/CREATED_BY").getBestTranslation()); ps.setLong(19, content.getValue(FxDateTime.class, "/CREATED_AT").getBestTranslation().getTime()); ps.setLong(20, content.getValue(FxLargeNumber.class, "/MODIFIED_BY").getBestTranslation()); ps.setLong(21, content.getValue(FxDateTime.class, "/MODIFIED_AT").getBestTranslation().getTime()); } ps.setLong(22, content.getMandatorId()); final String groupPositions = getGroupPositions(content); if (groupPositions != null) { StorageManager.getStorageImpl().setBigString(ps, 23, groupPositions); } else { ps.setNull(23, Types.CLOB); } ps.executeUpdate(); updateACLEntries(con, content, pk, true); } catch (SQLException e) { throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage()); } catch (FxUpdateException e) { throw new FxCreateException(e); } finally { Database.closeObjects(GenericHierarchicalStorage.class, ps); } return pk; }
From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
private ODataDataType getODataDataType(int columnType) { ODataDataType dataType;//from w ww . j av a 2s . c o m switch (columnType) { case Types.INTEGER: dataType = ODataDataType.INT32; break; case Types.TINYINT: /* fall through */ case Types.SMALLINT: dataType = ODataDataType.INT16; break; case Types.DOUBLE: dataType = ODataDataType.DOUBLE; break; case Types.VARCHAR: /* fall through */ case Types.CHAR: /* fall through */ case Types.LONGVARCHAR: /* fall through */ case Types.CLOB: /* fall through */ case Types.LONGNVARCHAR: /* fall through */ case Types.NCHAR: /* fall through */ case Types.NVARCHAR: /* fall through */ case Types.NCLOB: /* fall through */ case Types.SQLXML: dataType = ODataDataType.STRING; break; case Types.BOOLEAN: /* fall through */ case Types.BIT: dataType = ODataDataType.BOOLEAN; break; case Types.BLOB: /* fall through */ case Types.BINARY: /* fall through */ case Types.LONGVARBINARY: /* fall through */ case Types.VARBINARY: dataType = ODataDataType.BINARY; break; case Types.DATE: dataType = ODataDataType.DATE; break; case Types.DECIMAL: /* fall through */ case Types.NUMERIC: dataType = ODataDataType.DECIMAL; break; case Types.FLOAT: /* fall through */ case Types.REAL: dataType = ODataDataType.SINGLE; break; case Types.TIME: dataType = ODataDataType.TIMEOFDAY; break; case Types.BIGINT: dataType = ODataDataType.INT64; break; case Types.TIMESTAMP: dataType = ODataDataType.DATE_TIMEOFFSET; break; default: dataType = ODataDataType.STRING; break; } return dataType; }
From source file:it.greenvulcano.gvesb.datahandling.dbo.DBOCallSP.java
/** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, * java.lang.String, java.lang.String) *//* w ww .jav a2s. c o m*/ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (ROW_NAME.equals(localName)) { if (!currCriticalError) { executeStatement(); } else { rowDisc++; // aggiunta DiscardCause al dhr... String msg = currentXSLMessage; dhr.addDiscardCause(new DiscardCause(rowCounter, msg)); resultMessage.append("Data error on row ").append(rowCounter).append(": ").append(msg); resultMessage.append("SQL Statement Informations:\n").append(sqlStatementInfo); resultMessage.append("Record parameters:\n").append(dumpCurrentRowFields()); resultStatus = STATUS_PARTIAL; } } else if (COL_NAME.equals(localName)) { CallableStatement cs = (CallableStatement) sqlStatementInfo.getStatement(); try { if (!outOnly) { colDataExpecting = false; String text = textBuffer.toString(); if ((currentUUID != null) && (currentUUID.trim().length() > 0) && (text.length() == 0)) { text = uuids.get(currentUUID); if (text == null) { text = currentUUID; } } if (TIMESTAMP_TYPE.equals(currType) || DATE_TYPE.equals(currType) || TIME_TYPE.equals(currType)) { if (text.equals("")) { if (TIMESTAMP_TYPE.equals(currType)) setNull(cs, Types.TIMESTAMP); else if (DATE_TYPE.equals(currType)) setNull(cs, Types.DATE); else setNull(cs, Types.TIME); currentRowFields.add(null); } else { dateFormatter.applyPattern(currDateFormat); Date formattedDate = dateFormatter.parse(text); if (TIMESTAMP_TYPE.equals(currType)) { Timestamp ts = new Timestamp(formattedDate.getTime()); setTimestamp(cs, ts); currentRowFields.add(ts); } else if (DATE_TYPE.equals(currType)) { java.sql.Date d = new java.sql.Date(formattedDate.getTime()); setDate(cs, d); currentRowFields.add(d); } else { java.sql.Time t = new java.sql.Time(formattedDate.getTime()); setTime(cs, t); currentRowFields.add(t); } } } else if (INTEGER_TYPE.equals(currType) || SMALLINT_TYPE.equals(currType) || BIGINT_TYPE.equals(currType)) { if (text.equals("")) { if (INTEGER_TYPE.equals(currType)) setNull(cs, Types.INTEGER); else if (SMALLINT_TYPE.equals(currType)) setNull(cs, Types.SMALLINT); else setNull(cs, Types.BIGINT); currentRowFields.add(null); } else { if (INTEGER_TYPE.equals(currType)) setInt(cs, Integer.parseInt(text, 10)); else if (SMALLINT_TYPE.equals(currType)) setShort(cs, Short.parseShort(text, 10)); else setLong(cs, Long.parseLong(text, 10)); currentRowFields.add(text); } } else if (FLOAT_TYPE.equals(currType) || DOUBLE_TYPE.equals(currType) || DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { if (text.equals("")) { if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) setNull(cs, Types.NUMERIC); else if (FLOAT_TYPE.equals(currType)) setNull(cs, Types.FLOAT); else setNull(cs, Types.DOUBLE); currentRowFields.add(null); } else { DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols(); dfs.setDecimalSeparator(currDecSeparator.charAt(0)); dfs.setGroupingSeparator(currGroupSeparator.charAt(0)); numberFormatter.setDecimalFormatSymbols(dfs); numberFormatter.applyPattern(currNumberFormat); boolean isBigDecimal = numberFormatter.isParseBigDecimal(); try { numberFormatter.setParseBigDecimal(true); BigDecimal formattedNumber = (BigDecimal) numberFormatter.parse(text); if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { setBigDecimal(cs, formattedNumber); currentRowFields.add(formattedNumber); } else if (FLOAT_TYPE.equals(currType)) { setFloat(cs, formattedNumber.floatValue()); currentRowFields.add(formattedNumber.floatValue()); } else { setDouble(cs, formattedNumber.doubleValue()); currentRowFields.add(formattedNumber.doubleValue()); } } finally { numberFormatter.setParseBigDecimal(isBigDecimal); } } } else if (LONG_STRING_TYPE.equals(currType) || LONG_NSTRING_TYPE.equals(currType)) { if (text.equals("")) { if (LONG_STRING_TYPE.equals(currType)) setNull(cs, Types.CLOB); else setNull(cs, Types.NCLOB); currentRowFields.add(null); } else { if (LONG_STRING_TYPE.equals(currType)) { setCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } else { setNCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } } } else if (BASE64_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); data = Base64.getDecoder().decode(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BINARY_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BOOLEAN_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BOOLEAN); currentRowFields.add(null); } else { setBoolean(cs, TextUtils.parseBoolean(text)); currentRowFields.add(text); } } else if (XML_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.SQLXML); currentRowFields.add(null); } else { SQLXML xml = cs.getConnection().createSQLXML(); xml.setString(text); setSQLXML(cs, xml); currentRowFields.add(text); } } else if (NSTRING_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.NVARCHAR); currentRowFields.add(null); } else { setNString(cs, text); currentRowFields.add(text); } } else { if (text.equals("")) { setNull(cs, Types.VARCHAR); currentRowFields.add(null); } else { setString(cs, text); currentRowFields.add(text); } } } else { currentRowFields.add(currentUUID); } } catch (ParseException exc) { throw new SAXException(exc); } catch (SQLException exc) { OracleExceptionHandler.handleSQLException(exc); throw new SAXException(exc); } } }
From source file:com.flexive.ejb.beans.PhraseEngineBean.java
/** * {@inheritDoc}/*from w ww .j a v a2 s . c o m*/ */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void setPhraseTreeNodeParent(long nodeId, long nodeMandator, long parentId, long parentMandator) throws FxNoAccessException, FxNotFoundException { Connection con = null; PreparedStatement ps = null; checkMandatorAccess(nodeMandator, FxContext.getUserTicket()); try { // Obtain a database connection con = Database.getDbConnection(); //check if the node and the parent node exists ps = con.prepareStatement( "SELECT ID, MANDATOR, CAT FROM " + TBL_PHRASE_TREE + " WHERE ID=? AND MANDATOR=?"); ps.setLong(1, nodeId); ps.setLong(2, nodeMandator); ResultSet rs = ps.executeQuery(); if (!(rs != null && rs.next())) throw new FxNotFoundException("ex.phrases.node.notFound.id", nodeId, nodeMandator); final int nodeCategory = rs.getInt(3); final int parentCategory; if (parentId != FxPhraseTreeNode.NOT_SET) { ps.setLong(1, parentId); ps.setLong(2, parentMandator); rs = ps.executeQuery(); if (!(rs != null && rs.next())) throw new FxNotFoundException("ex.phrase.tree.parent.notFound", parentId, parentMandator); parentCategory = rs.getInt(3); } else parentCategory = nodeCategory; if (nodeCategory != parentCategory) throw new FxInvalidParameterException("parent", "ex.phrase.tree.category.mismatch") .asRuntimeException(); ps.close(); ps = con.prepareStatement( "UPDATE " + TBL_PHRASE_TREE + " SET PARENTID=?,PARENTMANDATOR=? WHERE ID=? AND MANDATOR=?"); if (parentId != FxPhraseTreeNode.NOT_SET) { ps.setLong(1, parentId); ps.setLong(2, parentMandator); } else { ps.setNull(1, Types.NUMERIC); ps.setNull(1, Types.NUMERIC); } ps.setLong(3, nodeId); ps.setLong(4, nodeMandator); ps.executeUpdate(); } catch (SQLException exc) { EJBUtils.rollback(ctx); throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage()).asRuntimeException(); } finally { Database.closeObjects(PhraseEngineBean.class, con, ps); } }
From source file:com.feedzai.commons.sql.abstraction.engine.AbstractDatabaseEngine.java
/** * Maps the database type to {@link DbColumnType}. If there's no mapping a {@link DbColumnType#UNMAPPED} is returned. * * @param type The SQL type from {@link java.sql.Types}. * @return The {@link DbColumnType}./*from w w w . j a v a2 s. co m*/ */ protected DbColumnType toPdbType(final int type) { switch (type) { case Types.ARRAY: return DbColumnType.UNMAPPED; case Types.BIGINT: return DbColumnType.LONG; case Types.BINARY: return DbColumnType.BLOB; case Types.BIT: return DbColumnType.BOOLEAN; case Types.BLOB: return DbColumnType.BLOB; case Types.BOOLEAN: return DbColumnType.BOOLEAN; case Types.CHAR: return DbColumnType.STRING; case Types.CLOB: return DbColumnType.STRING; case Types.DATALINK: return DbColumnType.UNMAPPED; case Types.DATE: return DbColumnType.UNMAPPED; case Types.DECIMAL: return DbColumnType.DOUBLE; case Types.DISTINCT: return DbColumnType.UNMAPPED; case Types.DOUBLE: return DbColumnType.DOUBLE; case Types.FLOAT: return DbColumnType.DOUBLE; case Types.INTEGER: return DbColumnType.INT; case Types.JAVA_OBJECT: return DbColumnType.BLOB; case Types.LONGNVARCHAR: return DbColumnType.STRING; case Types.LONGVARBINARY: return DbColumnType.BLOB; case Types.LONGVARCHAR: return DbColumnType.STRING; case Types.NCHAR: return DbColumnType.STRING; case Types.NCLOB: return DbColumnType.STRING; case Types.NULL: return DbColumnType.UNMAPPED; case Types.NUMERIC: return DbColumnType.DOUBLE; case Types.NVARCHAR: return DbColumnType.STRING; case Types.OTHER: return DbColumnType.UNMAPPED; case Types.REAL: return DbColumnType.DOUBLE; case Types.REF: return DbColumnType.UNMAPPED; case Types.ROWID: return DbColumnType.STRING; case Types.SMALLINT: return DbColumnType.INT; case Types.SQLXML: return DbColumnType.STRING; case Types.STRUCT: return DbColumnType.UNMAPPED; case Types.TIME: return DbColumnType.UNMAPPED; case Types.TIMESTAMP: return DbColumnType.LONG; case Types.TINYINT: return DbColumnType.INT; case Types.VARBINARY: return DbColumnType.BLOB; case Types.VARCHAR: return DbColumnType.STRING; default: return DbColumnType.UNMAPPED; } }
From source file:helma.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet.//from w w w . j a v a2 s .co m */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(safe); for (int i = 0; i < columns.length; i++) { int columnNumber = i + 1 + offset; // set prototype? if (columns[i].isPrototypeField()) { String protoId = rs.getString(columnNumber); protoName = dbm.getPrototypeName(protoId); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError("No prototype defined for prototype mapping \"" + protoName + "\" - Using default prototype \"" + dbm.getTypeName() + "\"."); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(columnNumber); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(columnNumber); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: case Types.BOOLEAN: newprop.setBooleanValue(rs.getBoolean(columnNumber)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(columnNumber)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(columnNumber)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(columnNumber); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: newprop.setJavaObjectValue(rs.getBytes(columnNumber)); break; case Types.BLOB: case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(columnNumber); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(columnNumber)); } catch (SQLException x) { Reader in = rs.getCharacterStream(columnNumber); if (in == null) { newprop.setStringValue(null); break; } StringBuffer out = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = in.read(buffer)) > -1) { out.append(buffer, 0, read); } newprop.setStringValue(out.toString()); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(columnNumber)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(columnNumber)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(columnNumber); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(columnNumber)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } else { Transactor tx = Transactor.getInstance(); if (tx != null) { // Check if the node is already registered with the transactor - // it may be in the process of being DELETED, but do return the // new node if the old one has been marked as INVALID. DbKey key = new DbKey(dbmap, id); Node dirtyNode = tx.getDirtyNode(key); if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) { return dirtyNode; } } } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && rel.isPrimitiveOrReference()) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if (rel.isReference() && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel); } propMap.put(rel.propName, prop); } } node.init(dbmap, id, name, protoName, propMap); return node; }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
@Mock private static void loadParameters(PreparedStatement statement, Collection<ColumnInfo> columns, TableRow row) throws SQLException { int count = 0; for (ColumnInfo info : columns) { count++;// w ww .j a va 2s. co m String column = info.getName(); int jdbctype = info.getType(); if (row.isColumnNull(column)) { statement.setNull(count, jdbctype); } else { switch (jdbctype) { case Types.BIT: case Types.BOOLEAN: statement.setBoolean(count, row.getBooleanColumn(column)); break; case Types.INTEGER: if (isOracle) { statement.setLong(count, row.getLongColumn(column)); } else { statement.setInt(count, row.getIntColumn(column)); } break; case Types.NUMERIC: case Types.DECIMAL: statement.setLong(count, row.getLongColumn(column)); // FIXME should be BigDecimal if TableRow supported that break; case Types.BIGINT: statement.setLong(count, row.getLongColumn(column)); break; case Types.CLOB: if (isOracle) { // Support CLOBs in place of TEXT columns in Oracle statement.setString(count, row.getStringColumn(column)); } else { throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } break; case Types.VARCHAR: statement.setString(count, row.getStringColumn(column)); break; case Types.DATE: statement.setDate(count, new java.sql.Date(row.getDateColumn(column).getTime())); break; case Types.TIME: statement.setTime(count, new Time(row.getDateColumn(column).getTime())); break; case Types.TIMESTAMP: statement.setTimestamp(count, new Timestamp(row.getDateColumn(column).getTime())); break; default: throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } } } }
From source file:com.manydesigns.portofino.actions.admin.appwizard.ApplicationWizard.java
protected void detectBooleanColumn(Table table, Column column) { if (detectedBooleanColumns.contains(column)) { return;//www .ja v a 2 s . com } if (column.getJdbcType() == Types.INTEGER || column.getJdbcType() == Types.DECIMAL || column.getJdbcType() == Types.NUMERIC) { logger.info("Detecting whether numeric column " + column.getQualifiedName() + " is boolean by examining " + "its values..."); // Detect booleans Connection connection = null; try { connection = connectionProvider.acquireConnection(); liquibase.database.Database implementation = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(new JdbcConnection(connection)); String sql = "select count(" + implementation.escapeDatabaseObject(column.getColumnName()) + ") " + "from " + implementation.escapeTableName(table.getSchemaName(), table.getTableName()); PreparedStatement statement = connection.prepareStatement(sql); setQueryTimeout(statement, 1); statement.setMaxRows(1); ResultSet rs = statement.executeQuery(); Long count = null; if (rs.next()) { count = safeGetLong(rs, 1); } if (count == null || count < 10) { logger.info("Cannot determine if numeric column {} is boolean, count is {}", column.getQualifiedName(), count); return; } sql = "select distinct(" + implementation.escapeDatabaseObject(column.getColumnName()) + ") " + "from " + implementation.escapeTableName(table.getSchemaName(), table.getTableName()); statement = connection.prepareStatement(sql); setQueryTimeout(statement, 1); statement.setMaxRows(3); rs = statement.executeQuery(); int valueCount = 0; boolean only0and1 = true; while (rs.next()) { valueCount++; if (valueCount > 2) { only0and1 = false; break; } Long value = safeGetLong(rs, 1); only0and1 &= value != null && (value == 0 || value == 1); } if (only0and1 && valueCount == 2) { logger.info("Column appears to be of boolean type."); column.setJavaType(Boolean.class.getName()); } else { logger.info("Column appears not to be of boolean type."); } statement.close(); } catch (Exception e) { logger.debug("Could not determine whether column " + column.getQualifiedName() + " is boolean", e); logger.info("Could not determine whether column " + column.getQualifiedName() + " is boolean"); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { logger.error("Could not close connection", e); } } detectedBooleanColumns.add(column); } }
From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java
/** * Return the preferred {@link Types} constant for the given * {@link JavaTypes} or {@link JavaSQLTypes} constant. *///from www . j a va 2 s. co m public int getJDBCType(int metaTypeCode, boolean lob, int precis, int scale) { if (lob) { switch (metaTypeCode) { case JavaTypes.STRING: case JavaSQLTypes.ASCII_STREAM: case JavaSQLTypes.CHAR_STREAM: return getPreferredType(Types.CLOB); default: return getPreferredType(Types.BLOB); } } switch (metaTypeCode) { case JavaTypes.BOOLEAN: case JavaTypes.BOOLEAN_OBJ: return getPreferredType(Types.BIT); case JavaTypes.BYTE: case JavaTypes.BYTE_OBJ: return getPreferredType(Types.TINYINT); case JavaTypes.CHAR: case JavaTypes.CHAR_OBJ: if (storeCharsAsNumbers) return getPreferredType(Types.INTEGER); return getPreferredType(Types.CHAR); case JavaTypes.DOUBLE: case JavaTypes.DOUBLE_OBJ: if (precis > 0 || scale > 0) { return getPreferredType(Types.NUMERIC); } else { return getPreferredType(Types.DOUBLE); } case JavaTypes.FLOAT: case JavaTypes.FLOAT_OBJ: if (precis > 0 || scale > 0) { return getPreferredType(Types.NUMERIC); } else { return getPreferredType(Types.REAL); } case JavaTypes.INT: case JavaTypes.INT_OBJ: return getPreferredType(Types.INTEGER); case JavaTypes.LONG: case JavaTypes.LONG_OBJ: return getPreferredType(Types.BIGINT); case JavaTypes.SHORT: case JavaTypes.SHORT_OBJ: return getPreferredType(Types.SMALLINT); case JavaTypes.STRING: case JavaTypes.LOCALE: case JavaSQLTypes.ASCII_STREAM: case JavaSQLTypes.CHAR_STREAM: return getPreferredType(Types.VARCHAR); case JavaTypes.BIGINTEGER: if (storeLargeNumbersAsStrings) return getPreferredType(Types.VARCHAR); return getPreferredType(Types.BIGINT); case JavaTypes.BIGDECIMAL: if (storeLargeNumbersAsStrings) return getPreferredType(Types.VARCHAR); return getPreferredType(Types.NUMERIC); case JavaTypes.NUMBER: if (storeLargeNumbersAsStrings) return getPreferredType(Types.VARCHAR); return getPreferredType(Types.NUMERIC); case JavaTypes.CALENDAR: case JavaTypes.DATE: return getPreferredType(Types.TIMESTAMP); case JavaSQLTypes.SQL_ARRAY: return getPreferredType(Types.ARRAY); case JavaSQLTypes.BINARY_STREAM: case JavaSQLTypes.BLOB: case JavaSQLTypes.BYTES: return getPreferredType(Types.BLOB); case JavaSQLTypes.CLOB: return getPreferredType(Types.CLOB); case JavaSQLTypes.SQL_DATE: return getPreferredType(Types.DATE); case JavaSQLTypes.TIME: return getPreferredType(Types.TIME); case JavaSQLTypes.TIMESTAMP: return getPreferredType(Types.TIMESTAMP); default: return getPreferredType(Types.BLOB); } }
From source file:helma.objectmodel.db.NodeManager.java
private void setStatementValue(PreparedStatement stmt, int stmtNumber, Property p, int columnType) throws SQLException { if (p.getValue() == null) { stmt.setNull(stmtNumber, columnType); } else {//from w w w.ja v a 2 s. c om switch (columnType) { case Types.BIT: case Types.BOOLEAN: stmt.setBoolean(stmtNumber, p.getBooleanValue()); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: stmt.setLong(stmtNumber, p.getIntegerValue()); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: stmt.setDouble(stmtNumber, p.getFloatValue()); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: case Types.BLOB: Object b = p.getJavaObjectValue(); if (b instanceof byte[]) { byte[] buf = (byte[]) b; try { stmt.setBytes(stmtNumber, buf); } catch (SQLException x) { ByteArrayInputStream bout = new ByteArrayInputStream(buf); stmt.setBinaryStream(stmtNumber, bout, buf.length); } } else { throw new SQLException( "expected byte[] for binary column '" + p.getName() + "', found " + b.getClass()); } break; case Types.LONGVARCHAR: try { stmt.setString(stmtNumber, p.getStringValue()); } catch (SQLException x) { String str = p.getStringValue(); Reader r = new StringReader(str); stmt.setCharacterStream(stmtNumber, r, str.length()); } break; case Types.CLOB: String val = p.getStringValue(); Reader isr = new StringReader(val); stmt.setCharacterStream(stmtNumber, isr, val.length()); break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: stmt.setString(stmtNumber, p.getStringValue()); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: stmt.setTimestamp(stmtNumber, p.getTimestampValue()); break; case Types.NULL: stmt.setNull(stmtNumber, 0); break; default: stmt.setString(stmtNumber, p.getStringValue()); break; } } }