Example usage for java.sql Types DATE

List of usage examples for java.sql Types DATE

Introduction

In this page you can find the example usage for java.sql Types DATE.

Prototype

int DATE

To view the source code for java.sql Types DATE.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type DATE.

Usage

From source file:CSVWriter.java

private static String getColumnValue(ResultSet rs, int colType, int colIndex)
    throws SQLException, IOException {

  String value = "";
      //  w  ww.  j  av  a  2  s.  co m
switch (colType)
{
  case Types.BIT:
    Object bit = rs.getObject(colIndex);
    if (bit != null) {
      value = String.valueOf(bit);
    }
  break;
  case Types.BOOLEAN:
    boolean b = rs.getBoolean(colIndex);
    if (!rs.wasNull()) {
      value = Boolean.valueOf(b).toString();
    }
  break;
  case Types.CLOB:
    Clob c = rs.getClob(colIndex);
    if (c != null) {
      value = read(c);
    }
  break;
  case Types.BIGINT:
  case Types.DECIMAL:
  case Types.DOUBLE:
  case Types.FLOAT:
  case Types.REAL:
  case Types.NUMERIC:
    BigDecimal bd = rs.getBigDecimal(colIndex);
    if (bd != null) {
      value = "" + bd.doubleValue();
    }
  break;
  case Types.INTEGER:
  case Types.TINYINT:
  case Types.SMALLINT:
    int intValue = rs.getInt(colIndex);
    if (!rs.wasNull()) {
      value = "" + intValue;
    }
  break;
  case Types.JAVA_OBJECT:
    Object obj = rs.getObject(colIndex);
    if (obj != null) {
      value = String.valueOf(obj);
    }
  break;
  case Types.DATE:
    java.sql.Date date = rs.getDate(colIndex);
    if (date != null) {
      value = DATE_FORMATTER.format(date);;
    }
  break;
  case Types.TIME:
    Time t = rs.getTime(colIndex);
    if (t != null) {
      value = t.toString();
    }
  break;
  case Types.TIMESTAMP:
    Timestamp tstamp = rs.getTimestamp(colIndex);
    if (tstamp != null) {
      value = TIMESTAMP_FORMATTER.format(tstamp);
    }
  break;
  case Types.LONGVARCHAR:
  case Types.VARCHAR:
  case Types.CHAR:
    value = rs.getString(colIndex);
  break;
  default:
    value = "";
}

    
if (value == null)
{
  value = "";
}
    
return value;
      
}

From source file:org.dashbuilder.dataprovider.sql.JDBCUtils.java

public static ColumnType calculateType(int sqlDataType) {
    switch (sqlDataType) {

    // Category-like columns.
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.NCHAR:
    case Types.NVARCHAR:
    case Types.BIT:
    case Types.BOOLEAN: {
        return ColumnType.LABEL;
    }/* w w  w  . j a  v  a 2  s.c o  m*/

    // Text-like columns.
    case Types.LONGVARCHAR:
    case Types.LONGNVARCHAR: {
        return ColumnType.TEXT;
    }

    // Number-like columns.
    case Types.TINYINT:
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.NUMERIC:
    case Types.REAL:
    case Types.SMALLINT: {
        return ColumnType.NUMBER;
    }

    // Date-like columns.
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP: {
        return ColumnType.DATE;
    }

    // Unsupported
    default: {
        return null;
    }
    }
}

From source file:org.apache.sqoop.tool.ImportTool.java

/**
 * Return the max value in the incremental-import test column. This
 * value must be numeric.//  w ww .  j  av  a  2s  . c  o  m
 */
private Object getMaxColumnId(SqoopOptions options) throws SQLException {
    StringBuilder sb = new StringBuilder();
    String query;

    sb.append("SELECT MAX(");
    sb.append(options.getIncrementalTestColumn());
    sb.append(") FROM ");

    if (options.getTableName() != null) {
        // Table import
        sb.append(options.getTableName());

        String where = options.getWhereClause();
        if (null != where) {
            sb.append(" WHERE ");
            sb.append(where);
        }
        query = sb.toString();
    } else {
        // Free form table based import
        sb.append("(");
        sb.append(options.getSqlQuery());
        sb.append(") sqoop_import_query_alias");

        query = sb.toString().replaceAll("\\$CONDITIONS", "(1 = 1)");
    }

    Connection conn = manager.getConnection();
    Statement s = null;
    ResultSet rs = null;
    try {
        LOG.info("Maximal id query for free form incremental import: " + query);
        s = conn.createStatement();
        rs = s.executeQuery(query);
        if (!rs.next()) {
            // This probably means the table is empty.
            LOG.warn("Unexpected: empty results for max value query?");
            return null;
        }

        ResultSetMetaData rsmd = rs.getMetaData();
        checkColumnType = rsmd.getColumnType(1);
        if (checkColumnType == Types.TIMESTAMP) {
            return rs.getTimestamp(1);
        } else if (checkColumnType == Types.DATE) {
            return rs.getDate(1);
        } else if (checkColumnType == Types.TIME) {
            return rs.getTime(1);
        } else {
            return rs.getObject(1);
        }
    } finally {
        try {
            if (null != rs) {
                rs.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("SQL Exception closing resultset: " + sqlE);
        }

        try {
            if (null != s) {
                s.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("SQL Exception closing statement: " + sqlE);
        }
    }
}

From source file:com.gs.obevo.db.apps.reveng.CsvStaticDataWriter.java

private void writeTable(DbPlatform dbtype, PhysicalSchema schema, String tableName, File directory,
        MutableSet<String> updateTimeColumns, final CSVFormat csvFormat) {
    directory.mkdirs();//from  w w w.j  a va2 s .  c  om
    DaTable table = this.metadataManager.getTableInfo(schema.getPhysicalName(), tableName,
            new DaSchemaInfoLevel().setRetrieveTableColumns(true));
    if (table == null) {
        System.out.println("No data found for table " + tableName);
        return;
    }
    MutableList<String> columnNames = table.getColumns().collect(DaNamedObject.TO_NAME).toList();
    final String updateTimeColumnForTable = updateTimeColumns == null ? null
            : updateTimeColumns.detect(Predicates.in(columnNames));
    if (updateTimeColumnForTable != null) {
        columnNames.remove(updateTimeColumnForTable);
        System.out.println("Will mark " + updateTimeColumnForTable + " as an updateTimeColumn on this table");
    }

    final File tableFile = new File(directory, tableName + ".csv");
    final String selectSql = String.format("SELECT %s FROM %s%s", columnNames.makeString(", "),
            dbtype.getSchemaPrefix(schema), tableName);

    // using the jdbcTempate and ResultSetHandler to avoid sql-injection warnings in findbugs
    sqlExecutor.executeWithinContext(schema, new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            sqlExecutor.getJdbcTemplate().query(conn, selectSql, new ResultSetHandler<Void>() {
                @Override
                public Void handle(ResultSet rs) throws SQLException {
                    CSVPrinter writer = null;
                    try {
                        FileWriter fw = new FileWriter(tableFile);
                        writer = new CSVPrinter(fw, csvFormat);

                        if (updateTimeColumnForTable != null) {
                            String metadataLine = String.format("//// METADATA %s=\"%s\"",
                                    TextMarkupDocumentReader.ATTR_UPDATE_TIME_COLUMN, updateTimeColumnForTable);
                            fw.write(metadataLine + "\n"); // writing using the FileWriter directly to avoid having the quotes
                            // delimited
                        }

                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

                        int columnCount = rs.getMetaData().getColumnCount();

                        // print headers
                        for (int i = 1; i <= columnCount; ++i) {
                            writer.print(rs.getMetaData().getColumnName(i));
                        }
                        writer.println();

                        while (rs.next()) {
                            for (int i = 1; i <= columnCount; ++i) {
                                Object object = rs.getObject(i);
                                if (object != null) {
                                    switch (rs.getMetaData().getColumnType(i)) {
                                    case Types.DATE:
                                        object = dateFormat.format(object);
                                        break;
                                    case Types.TIMESTAMP:
                                        object = dateTimeFormat.format(object);
                                        break;
                                    case Types.LONGVARCHAR:
                                    case Types.VARCHAR:
                                    case Types.CHAR:
                                        // escape the string text if declared so that the input CSV can also handle the escapes
                                        if (csvFormat.getEscapeCharacter() != null
                                                && object instanceof String) {
                                            object = ((String) object).replace(
                                                    "" + csvFormat.getEscapeCharacter(),
                                                    "" + csvFormat.getEscapeCharacter()
                                                            + csvFormat.getEscapeCharacter());
                                        }
                                        break;
                                    }
                                }
                                writer.print(object);
                            }

                            writer.println();
                        }

                        writer.flush();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        IOUtils.closeQuietly(writer);
                    }

                    return null;
                }
            });
        }
    });

    int blankFileSize = updateTimeColumnForTable == null ? 1 : 2;

    if (!tableFile.canRead() || FileUtilsCobra.readLines(tableFile).size() <= blankFileSize) {
        System.out.println("No data found for table " + tableName + "; will clean up file");
        FileUtils.deleteQuietly(tableFile);
    }
}

From source file:org.jasig.ssp.util.importer.job.validation.map.metadata.database.MapColumnMetadata.java

public Object convertValueToType(String columnValue, MapReference mapReference,
        DatabaseConstraintMapValidationContext validation) {
    Object propertyValue = null;//from   ww  w  .ja  va2  s  .com
    String typeAsString = "";
    if (columnValue != null) {
        try {
            switch (javaSqlType) {
            case Types.BIGINT:
                typeAsString = "BIGINT";
                propertyValue = Long.parseLong(columnValue);
                break;
            case Types.INTEGER:
                typeAsString = "INTEGER";
                propertyValue = Integer.parseInt(columnValue);
                break;
            case Types.DECIMAL:
                typeAsString = "DECIMAL";
            case Types.DOUBLE:
                typeAsString = "DOUBLE";
            case Types.FLOAT:
                typeAsString = "FLOAT";
            case Types.NUMERIC:
                typeAsString = "NUMERIC";
                propertyValue = new BigDecimal(columnValue);
                break;

            case Types.DATE:
                typeAsString = "DATE";
                propertyValue = DateUtils.parseDateStrictly(columnValue, DATE_PATTERNS);
                break;
            case Types.TIMESTAMP:
                typeAsString = "TIMESTAMP";
                propertyValue = new java.sql.Timestamp(Long.getLong(columnValue));
                break;
            case Types.TIME:
                typeAsString = "TIME";
                propertyValue = new Time(DateUtils.parseDateStrictly(columnValue, TIME_PATTERNS).getTime());
                break;
            default:
                typeAsString = javaSqlType.toString();
                propertyValue = columnValue;
                break;

            }
        } catch (Exception exception) {
            validation.addViolation(new UnableToParseMapViolation(mapReference, columnValue, typeAsString));
            propertyValue = columnValue;
        }

    }
    return propertyValue;
}

From source file:org.akaza.openclinica.dao.managestudy.StudyDAO.java

/**
 * <P>//from ww w.j a  v  a2s.  com
 * updateStepOne, the update method for the database. This method takes the
 * place of createStepOne, since it runs an update and assumes you already
 * have a primary key in the study bean object.
 * 
 * @param sb
 *            the study bean which will be updated.
 * @return sb the study bean after it is updated with this phase.
 */
public StudyBean updateStepOne(StudyBean sb) {
    HashMap variables = new HashMap();
    HashMap nullVars = new HashMap();

    if (sb.getParentStudyId() == 0) {
        nullVars.put(new Integer(1), new Integer(Types.INTEGER));
        variables.put(new Integer(1), null);
    } else {
        variables.put(new Integer(1), new Integer(sb.getParentStudyId()));
    }
    variables.put(new Integer(2), sb.getName());
    variables.put(new Integer(3), sb.getOfficialTitle());
    variables.put(new Integer(4), sb.getIdentifier());
    variables.put(new Integer(5), sb.getSecondaryIdentifier());
    variables.put(new Integer(6), sb.getSummary());
    variables.put(new Integer(7), sb.getPrincipalInvestigator());
    if (sb.getDatePlannedStart() == null) {
        nullVars.put(new Integer(8), new Integer(Types.DATE));
        variables.put(new Integer(8), null);
    } else {
        variables.put(new Integer(8), sb.getDatePlannedStart());
    }

    if (sb.getDatePlannedEnd() == null) {
        nullVars.put(new Integer(9), new Integer(Types.DATE));
        variables.put(new Integer(9), null);
    } else {
        variables.put(new Integer(9), sb.getDatePlannedEnd());
    }

    variables.put(new Integer(10), sb.getFacilityName());
    variables.put(new Integer(11), sb.getFacilityCity());
    variables.put(new Integer(12), sb.getFacilityState());
    variables.put(new Integer(13), sb.getFacilityZip());
    variables.put(new Integer(14), sb.getFacilityCountry());
    variables.put(new Integer(15), sb.getFacilityRecruitmentStatus());
    variables.put(new Integer(16), sb.getFacilityContactName());
    variables.put(new Integer(17), sb.getFacilityContactDegree());
    variables.put(new Integer(18), sb.getFacilityContactPhone());
    variables.put(new Integer(19), sb.getFacilityContactEmail());
    variables.put(new Integer(20), new Integer(sb.getStatus().getId()));// status
    // id
    // variables.put(new Integer(19), sb.getStatus())//need to get a
    // function
    // to get the id
    // variables.put(new Integer(19), sb.getCreatedDate());
    variables.put(new Integer(21), new Integer(sb.getUpdaterId()));// owner
    // id
    if (sb.getUpdatedDate() == null) {
        nullVars.put(new Integer(22), new Integer(Types.DATE));
        variables.put(new Integer(22), null);
    } else {
        variables.put(new Integer(22), sb.getUpdatedDate());
    }
    variables.put(new Integer(23), new Integer(sb.getOldStatus().getId()));// study id
    // variables.put(new Integer(22), new Integer(1));
    // stop gap measure for owner and updater id
    variables.put(new Integer(24), new Integer(sb.getId()));// study id
    this.execute(digester.getQuery("updateStepOne"), variables, nullVars);
    return sb;
}

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java

private String getValues(final ResultSet rs, final String columnName, final Integer columnType)
        throws SQLException {

    String res = null;//from w w w . ja va  2s  . c  o  m

    try {
        switch (columnType) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            final InputStream is = rs.getBinaryStream(columnName);
            if (is != null) {
                res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(is));
            }
            break;

        case Types.BLOB:
            final Blob blob = rs.getBlob(columnName);
            if (blob != null) {
                res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(blob.getBinaryStream()));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            if (rs.getBoolean(columnName)) {
                res = "1";
            } else {
                res = "0";
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnName);
            if (timestamp != null) {
                res = FormatUtils.format(new Date(timestamp.getTime()));
            }
            break;

        default:
            res = rs.getString(columnName);
        }
    } catch (IOException e) {
        LOG.error("Error retrieving hexadecimal string", e);
    }

    return res;
}

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  ww .j ava2  s  . c  o  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.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java

private void updateIdeaInstance(IdeaInstance ideainstance, Connection conn) {
    PreparedStatement stat = null;
    try {/*from   www.  ja va 2s  .  c  o m*/
        stat = conn.prepareStatement(UPDATE_IDEAINSTANCE);
        int index = 1;
        if (null != ideainstance.getCreatedat()) {
            Timestamp createdatTimestamp = new Timestamp(ideainstance.getCreatedat().getTime());
            stat.setTimestamp(index++, createdatTimestamp);
        } else {
            stat.setNull(index++, Types.DATE);
        }
        stat.setString(index++, ideainstance.getCode());
        stat.executeUpdate();
    } catch (Throwable t) {
        _logger.error("Error updating ideainstance ", t);
        throw new RuntimeException("Error updating ideainstance ", t);
    } finally {
        this.closeDaoResources(null, stat, null);
    }
}

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  ww w  . ja  v a  2 s  .c  om
        return null;
    }
}