Example usage for java.sql Types INTEGER

List of usage examples for java.sql Types INTEGER

Introduction

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

Prototype

int INTEGER

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

Click Source Link

Document

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

Usage

From source file:net.chrisrichardson.bankingExample.domain.jdbc.JdbcAccountDao.java

public void saveAccount(Account account) {
    int count = jdbcTemplate.update(
            "UPDATE BANK_ACCOUNT set accountId = ?, BALANCE = ?, overdraftPolicy = ?, dateOpened = ?, requiredYearsOpen = ?, limit = ? WHERE ACCOUNT_ID = ?",
            new Object[] { account.getAccountId(), account.getBalance(), account.getOverdraftPolicy(),
                    new Timestamp(account.getDateOpened().getTime()), account.getRequiredYearsOpen(),
                    account.getLimit(), account.getId() },
            new int[] { Types.VARCHAR, Types.DOUBLE, Types.INTEGER, Types.TIMESTAMP, Types.DOUBLE, Types.DOUBLE,
                    Types.INTEGER });
    Assert.isTrue(count == 1);/*w w w . ja v a 2  s  .  c  o m*/

}

From source file:com.bigdata.etl.util.DwUtil.java

public static void bulkInsert(String tableName, List<Map<String, String>> lst) {

    ResultSet rs = null;/*from w  ww.j  a v  a2  s . c o m*/
    java.sql.Statement stmt = null;

    try (java.sql.Connection conn = DataSource.getConnection()) {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("select top 0 * from " + tableName);
        try (SQLServerBulkCopy bulk = new SQLServerBulkCopy(url + "user=" + user + ";password=" + password)) {
            SQLServerBulkCopyOptions sqlsbc = new SQLServerBulkCopyOptions();
            sqlsbc.setBulkCopyTimeout(60 * 60 * 1000);
            bulk.setBulkCopyOptions(sqlsbc);
            bulk.setDestinationTableName(tableName);
            ResultSetMetaData rsmd = rs.getMetaData();
            if (lst == null) {
                return;
            }
            // System.out.println(LocalTime.now() + " "+Thread.currentThread().getId()+" "+lst.size());
            try (CachedRowSetImpl x = new CachedRowSetImpl()) {
                x.populate(rs);
                for (int k = 0; k < lst.size(); k++) {
                    Map<String, String> map = lst.get(k);
                    x.last();
                    x.moveToInsertRow();
                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        String name = rsmd.getColumnName(i).toUpperCase();
                        int type = rsmd.getColumnType(i);//package java.sql.Type?

                        try {
                            switch (type) {
                            case Types.VARCHAR:
                            case Types.NVARCHAR:
                                int len = rsmd.getColumnDisplaySize(i);
                                String v = map.get(name);
                                if (map.containsKey(name)) {
                                    x.updateString(i, v.length() > len ? v.substring(0, len) : v);
                                } else {
                                    x.updateNull(i);
                                }
                                break;
                            case Types.BIGINT:
                                if (map.containsKey(name) && map.get(name).matches("\\d{1,}")) {
                                    x.updateLong(i, Long.valueOf(map.get(name)));
                                } else {
                                    //   x.updateLong(i, 0);
                                    x.updateNull(i);
                                }
                                break;
                            case Types.FLOAT:
                                if (map.containsKey(name) && map.get(name).matches("([+-]?)\\d*\\.\\d+$")) {
                                    x.updateFloat(i, Float.valueOf(map.get(name)));
                                } else {
                                    x.updateNull(i);

                                }
                                break;
                            case Types.DOUBLE:
                                if (map.containsKey(name) && map.get(name).trim().length() > 0
                                        && StringUtils.isNumeric(map.get(name))) {
                                    x.updateDouble(i, Double.valueOf(map.get(name)));
                                } else {
                                    x.updateNull(i);
                                }
                                break;

                            case Types.INTEGER:
                                if (map.containsKey(name) && map.get(name).matches("\\d{1,}")) {
                                    x.updateInt(i, Integer.valueOf(map.get(name)));
                                } else {
                                    x.updateNull(i);
                                }
                                break;

                            default:
                                throw new RuntimeException("? " + type);
                            }
                            /*
                            if(map.containsKey("SYS_TELECOM"))
                            System.err.println(map.get("SYS_TELECOM"));
                             */
                        } catch (RuntimeException | SQLException e) {
                            Logger.getLogger(DwUtil.class.getName()).log(Level.SEVERE,
                                    "? name=" + name + " v=" + map.get(name), e);
                        }

                    }
                    x.insertRow();
                    x.moveToCurrentRow();
                    //x.acceptChanges();
                }

                long start = System.currentTimeMillis();
                bulk.writeToServer(x);
                long end = System.currentTimeMillis();
                System.out.println(LocalTime.now() + " " + Thread.currentThread().getId() + " "
                        + (end - start) + "ms" + " " + x.size());
            }
        }

    } catch (SQLException e) {
        Logger.getLogger(DwUtil.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DwUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:de.whs.poodle.repositories.ExerciseRepository.java

public void save(Exercise exercise) {
    if (exercise.getTitle().trim().isEmpty())
        throw new BadRequestException("noTitleSpecified");
    if (exercise.getText().trim().isEmpty())
        throw new BadRequestException("noExerciseTextSpecified");

    jdbc.execute(new ConnectionCallback<Void>() {

        @Override/*from www  .  j  a va  2  s  . c o m*/
        public Void doInConnection(Connection con) throws SQLException, DataAccessException {
            try (CallableStatement exercisePs = con
                    .prepareCall("{ ? = CALL create_exercise(?,?,?::exercise_visibility,?,?,?,?,?,?,?,?,?) }");

                    PreparedStatement tagsPs = con
                            .prepareStatement("INSERT INTO exercise_to_tag(exercise_id,tag_id) VALUES(?,?)");) {
                con.setAutoCommit(false);

                // inner try for rollback
                try {
                    // create exercise
                    exercisePs.registerOutParameter(1, Types.INTEGER); // new_id

                    exercisePs.setString(2, exercise.getText());

                    /*
                     * The root id is always the ID of the first revision. If this
                     * is a new exercise, this ID obviously doesn't exist yet. We set
                     * NULL in this case, but a trigger in the DB will automatically
                     * set the root_id to the generated id.
                     */
                    if (exercise.getRootId() == 0)
                        exercisePs.setNull(3, Types.INTEGER);
                    else
                        exercisePs.setInt(3, exercise.getRootId());

                    exercisePs.setString(4, exercise.getVisibility().toString());
                    exercisePs.setString(5, exercise.getTitle());
                    exercisePs.setInt(6, exercise.getChangedBy().getId());
                    exercisePs.setString(7, exercise.getHint1());
                    exercisePs.setString(8, exercise.getHint2());

                    // sample solution
                    SampleSolutionType sampleSolutionType = exercise.getSampleSolutionType();

                    if (sampleSolutionType == SampleSolutionType.NONE) {
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else if (sampleSolutionType == SampleSolutionType.FILE) {
                        exercisePs.setInt(9, exercise.getSampleSolution().getFile().getId());
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else { // must be text
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setString(10, exercise.getSampleSolution().getText());
                    }

                    // attachments
                    List<Integer> attachmentIds = exercise.getAttachments().stream().map(a -> a.getId())
                            .collect(Collectors.toList());

                    Array anhaengeIdsArray = con.createArrayOf("int4", attachmentIds.toArray());
                    exercisePs.setArray(11, anhaengeIdsArray);

                    exercisePs.setInt(12, exercise.getCourseId());

                    exercisePs.setString(13, exercise.getComment());

                    exercisePs.executeUpdate();

                    /* Set the generated ID so the calling function can read it. */
                    exercise.setId(exercisePs.getInt(1));

                    // create relation to tags
                    tagsPs.setInt(1, exercise.getId());

                    for (Tag t : exercise.getTags()) {
                        tagsPs.setInt(2, t.getId());
                        tagsPs.addBatch();
                    }

                    tagsPs.executeBatch();

                    con.commit();
                } catch (SQLException e) {
                    con.rollback();
                    throw e;
                } finally {
                    con.setAutoCommit(true);
                }
            }

            return null;
        }
    });
}

From source file:com.squid.core.jdbc.formatter.DefaultJDBCDataFormatter.java

public String formatJDBCObject(final Object jdbcObject, final int colType) throws SQLException {
    String value = "";

    switch (colType) {
    case Types.BIT:
        if (jdbcObject != null) {
            value = String.valueOf(jdbcObject);
        }/*from   ww w  . j a v a  2  s  .  c om*/
        break;
    case Types.BOOLEAN:
        if (jdbcObject != null) {
            value = new Boolean(jdbcObject.toString()).toString();
        }
        break;
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.REAL:
    case Types.NUMERIC:
        if (jdbcObject != null) {
            value = "" + formatter.formatDecimal(jdbcObject);
        }
        break;
    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
        if (jdbcObject != null) {
            value = "" + formatter.formatDecimal(jdbcObject);
        }
        break;
    case Types.CLOB:
        if (jdbcObject != null) {
            try {
                value = read((Clob) jdbcObject);
            } catch (SQLException sqle) {
                value = "";
            } catch (IOException ioe) {
                value = "";
            }
        }
        break;
    case Types.ARRAY:
        try {
            ResultSet rs = ((Array) jdbcObject).getResultSet();
            int arrayType = ((Array) jdbcObject).getBaseType();
            boolean isNotNew = false;
            while (rs.next()) {
                String current = formatJDBCObject(rs.getObject(2), arrayType);
                if ("".equals(current.trim()) == false) {
                    if (isNotNew) {
                        value = value + ",";
                    } else {
                        isNotNew = !isNotNew;
                    }
                    value = value + current;
                }
            }
            if ("".equals(value) == false) {
                value = "{" + value + "}";
            }
        } catch (SQLException sqle) {
            value = "";
        }
        break;
    case Types.JAVA_OBJECT:
        if (jdbcObject != null) {
            value = String.valueOf(jdbcObject);
        }
        break;
    case Types.DATE:
        if (jdbcObject != null) {
            value = formatter.formatDate(jdbcObject);
        }
        break;
    case Types.TIME:
        if (jdbcObject != null) {
            value = ((Time) jdbcObject).toString();
        }
        break;
    case Types.TIMESTAMP:
        if (jdbcObject != null) {
            value = formatter.formatTimestamp(jdbcObject);
        }
        break;
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.CHAR:
        if (jdbcObject != null) {
            value = jdbcObject.toString();
        } else {
            value = "NULL";
        }
        break;
    case Types.BINARY:
        value = new String((byte[]) jdbcObject);
        break;
    default:
        value = "";
    }
    if (value == null) {
        value = "";
    }
    return value;
}

From source file:ResultsDecoratorSQL.java

public void write(ResultSet rs) throws IOException, SQLException {
    ResultSetMetaData md = rs.getMetaData();
    // This assumes you're not using a Join!!
    String tableName = md.getTableName(1);
    int cols = md.getColumnCount();
    StringBuffer sb = new StringBuffer("insert into ").append(tableName).append("(");
    for (int i = 1; i <= cols; i++) {
        sb.append(md.getColumnName(i));//from  w  ww .  j  a  v  a  2s  .  co  m
        if (i != cols) {
            sb.append(", ");
        }
    }
    sb.append(") values (");
    String insertCommand = sb.toString();
    while (rs.next()) {
        println(insertCommand);
        for (int i = 1; i <= cols; i++) {
            String tmp = rs.getString(i);
            if (rs.wasNull()) {
                print("null");
            } else {
                int type = md.getColumnType(i);
                // Don't quote numeric types; quote all others for now.
                switch (type) {
                case Types.BIGINT:
                case Types.DECIMAL:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.INTEGER:
                    print(tmp);
                    break;
                default:
                    tmp = tmp.replaceAll("'", "''");
                    print("'" + tmp + "'");
                }
            }
            if (i != cols) {
                print(", ");
            }
        }
        println(");");
    }
}

From source file:au.com.ish.derbydump.derbydump.metadata.Column.java

/**
 * Get a string value for the value in this column in the datarow
 * /*from  w w w.  ja v a2  s . com*/
 * @param dataRow The row which we are exporting
 * @return an SQL statement compliant string version of the value
 */
public String toString(ResultSet dataRow) throws SQLException {

    switch (getColumnDataType()) {
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.BLOB: {
        Blob obj = dataRow.getBlob(columnName);
        return (obj == null) ? "NULL" : processBinaryData(obj);
    }

    case Types.CLOB: {
        Clob obj = dataRow.getClob(columnName);
        return (obj == null) ? "NULL" : processClobData(obj);
    }

    case Types.CHAR:
    case Types.LONGNVARCHAR:
    case Types.VARCHAR: {
        String obj = dataRow.getString(columnName);
        return (obj == null) ? "NULL" : processStringData(obj);
    }

    case Types.TIME: {
        Time obj = dataRow.getTime(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.DATE: {
        Date obj = dataRow.getDate(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.TIMESTAMP: {
        Timestamp obj = dataRow.getTimestamp(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.SMALLINT: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.BIGINT: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.INTEGER: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.NUMERIC:
    case Types.DECIMAL: {
        BigDecimal obj = dataRow.getBigDecimal(columnName);
        return (obj == null) ? "NULL" : String.valueOf(obj);
    }

    case Types.REAL:
    case Types.FLOAT: {
        Float obj = dataRow.getFloat(columnName);
        // dataRow.getFloat() always returns a value. only way to check the null is wasNull() method
        return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj);
    }

    case Types.DOUBLE: {
        Double obj = dataRow.getDouble(columnName);
        return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj);
    }

    default: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }
    }
}

From source file:ar.com.zauber.commons.gis.spots.impl.SQLGeonameSpotDAO.java

/** @see GeonameSpotDAO#getSpotsWithNameLike(String) */
public final Collection<GeonameSpot> getSpotsWithNameLike(final String name, final Paging paging) {
    String ansiname = LatinStringUtils.replaceAccents(name);
    String sql = SELECT_WHAT + " WHERE ansiname ~* ? ORDER BY ansiname";
    Object[] objs;//w  w w.  ja  v  a 2  s. c  o m
    int[] classes;

    if (paging == null) {
        objs = new Object[] { ansiname };
        classes = new int[] { Types.VARCHAR };
    } else {
        sql += " LIMIT ? OFFSET ?";
        objs = new Object[] { ansiname, paging.getResultsPerPage(), paging.getFirstResult() };
        classes = new int[] { Types.VARCHAR, Types.INTEGER, Types.INTEGER };

        if (paging.loadResultSize()) {
            paging.setResultSize((int) getCountSpotsWithNameLike(ansiname));
        }
    }

    return (Collection<GeonameSpot>) jdbcTemplate.query(sql, objs, classes,
            new GeonameSpotExtractor(wktReader));
}

From source file:architecture.ee.web.logo.dao.jdbc.JdbcLogoImageDao.java

public void addLogoImage(LogoImage logoImage, InputStream is) {
    LogoImage toUse = logoImage;/*from  w w w .ja v a 2s . co m*/
    long logoIdToUse = logoImage.getLogoId();
    if (logoIdToUse < 1) {
        logoIdToUse = getNextId(sequencerName);
        logoImage.setLogoId(logoIdToUse);
    }

    getExtendedJdbcTemplate().update(
            getBoundSql("ARCHITECTURE_WEB.RESET_LOGO_IMAGE_BY_OBJECT_TYPE_AND_OBJECT_ID").getSql(),
            new SqlParameterValue(Types.INTEGER, toUse.getObjectType()),
            new SqlParameterValue(Types.NUMERIC, toUse.getObjectId()));

    getExtendedJdbcTemplate().update(getBoundSql("ARCHITECTURE_WEB.CREATE_LOGO_IMAGE").getSql(),
            new SqlParameterValue(Types.NUMERIC, logoImage.getLogoId()),
            new SqlParameterValue(Types.NUMERIC, logoImage.getObjectType()),
            new SqlParameterValue(Types.NUMERIC, logoImage.getObjectId()),
            new SqlParameterValue(Types.NUMERIC, logoImage.isPrimary() ? 1 : 0),
            new SqlParameterValue(Types.VARCHAR, logoImage.getFilename()),
            new SqlParameterValue(Types.NUMERIC, logoImage.getImageSize()),
            new SqlParameterValue(Types.VARCHAR, logoImage.getImageContentType()),
            new SqlParameterValue(Types.DATE, logoImage.getModifiedDate()),
            new SqlParameterValue(Types.DATE, logoImage.getCreationDate()));
    updateImageImputStream(logoImage, is);
}

From source file:com.hangum.tadpole.engine.sql.util.RDBTypeToJavaTypeUtils.java

/**
 * ? ?// w  w w  .j  a v  a  2 s. c  om
 * 
 * @param sqlType
 * @return
 */
public static boolean isNumberType(int sqlType) {
    switch (sqlType) {
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.INTEGER:
    case Types.NUMERIC:
    case Types.BIT:
    case Types.SMALLINT:
    case Types.TINYINT:
        return true;
    }

    return false;
}

From source file:com.streamsets.pipeline.stage.executor.jdbc.TestJdbcQueryExecutor.java

@Test
public void testEL() throws Exception {
    JdbcQueryExecutor queryExecutor = createExecutor(
            "CREATE TABLE ${record:value('/table')} AS SELECT * FROM origin");

    ExecutorRunner runner = new ExecutorRunner.Builder(JdbcQueryDExecutor.class, queryExecutor)
            .setOnRecordError(OnRecordError.STOP_PIPELINE).build();
    runner.runInit();// ww w  . jav  a  2 s.co m

    Map<String, Field> map = new HashMap<>();
    map.put("table", Field.create("el"));

    Record record = RecordCreator.create();
    record.set(Field.create(map));

    runner.runWrite(ImmutableList.of(record));
    runner.runDestroy();

    assertTableStructure("el", new ImmutablePair("ID", Types.INTEGER),
            new ImmutablePair("NAME", Types.VARCHAR));
}