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:com.sangupta.fileanalysis.db.DBResultViewer.java

/**
 * View resutls of a {@link ResultSet}.//  w w  w  . j  a  v  a 2s  .c  o m
 * 
 * @param resultSet
 * @throws SQLException 
 */
public void viewResult(ResultSet resultSet) throws SQLException {
    if (resultSet == null) {
        // nothing to do
        return;
    }

    // collect the meta
    ResultSetMetaData meta = resultSet.getMetaData();

    final int numColumns = meta.getColumnCount();
    final int[] displaySizes = new int[numColumns + 1];
    final int[] colType = new int[numColumns + 1];

    for (int index = 1; index <= numColumns; index++) {
        colType[index] = meta.getColumnType(index);
        displaySizes[index] = getColumnSize(meta.getTableName(index), meta.getColumnName(index),
                colType[index]);
    }

    // display the header row
    for (int index = 1; index <= numColumns; index++) {
        center(meta.getColumnLabel(index), displaySizes[index]);
    }
    System.out.println("|");
    for (int index = 1; index <= numColumns; index++) {
        System.out.print("+" + StringUtils.repeat('-', displaySizes[index] + 2));
    }
    System.out.println("+");

    // start iterating over the result set
    int rowsDisplayed = 0;
    int numRecords = 0;
    while (resultSet.next()) {
        // read and display the value
        rowsDisplayed++;
        numRecords++;

        for (int index = 1; index <= numColumns; index++) {
            switch (colType[index]) {
            case Types.DECIMAL:
            case Types.DOUBLE:
            case Types.REAL:
                format(resultSet.getDouble(index), displaySizes[index]);
                continue;

            case Types.INTEGER:
            case Types.SMALLINT:
                format(resultSet.getInt(index), displaySizes[index]);
                continue;

            case Types.VARCHAR:
                format(resultSet.getString(index), displaySizes[index], false);
                continue;

            case Types.TIMESTAMP:
                format(resultSet.getTimestamp(index), displaySizes[index]);
                continue;

            case Types.BIGINT:
                format(resultSet.getBigDecimal(index), displaySizes[index]);
                continue;
            }
        }

        // terminator for row and new line
        System.out.println("|");

        // check for rows displayed
        if (rowsDisplayed == 20) {
            // ask the user if more data needs to be displayed
            String cont = ConsoleUtils.readLine("Type \"it\" for more: ", true);
            if (!"it".equalsIgnoreCase(cont)) {
                break;
            }

            // continue;
            rowsDisplayed = 0;
            continue;
        }
    }

    System.out.println("\nTotal number of records found: " + numRecords);
}

From source file:ca.sqlpower.sqlobject.TestSQLTable.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    sqlx("CREATE TABLE REGRESSION_TEST1 (t1_c1 numeric(10), t1_c2 numeric(5))");
    sqlx("CREATE TABLE REGRESSION_TEST2 (t2_c1 char(10))");
    sqlx("CREATE VIEW REGRESSION_TEST1_VIEW AS SELECT * FROM REGRESSION_TEST1");

    sqlx("CREATE TABLE SQL_TABLE_POPULATE_TEST (\n" + " cow numeric(10) NOT NULL, \n"
            + " CONSTRAINT test4pk PRIMARY KEY (cow))");
    sqlx("CREATE TABLE SQL_TABLE_1_POPULATE_TEST (\n" + " cow numeric(10) NOT NULL, \n"
            + " CONSTRAINT test5pk PRIMARY KEY(cow))");
    sqlx("ALTER TABLE SQL_TABLE_1_POPULATE_TEST " + "ADD CONSTRAINT TEST_FK FOREIGN KEY (cow) "
            + "REFERENCES SQL_TABLE_POPULATE_TEST (cow)");

    table = new SQLTable(null, true);
    table.setParent(new StubSQLObject());

    table.addColumn(new SQLColumn(table, "one", Types.INTEGER, 10, 0));
    table.addColumn(new SQLColumn(table, "two", Types.INTEGER, 10, 0));
    table.addColumn(new SQLColumn(table, "three", Types.INTEGER, 10, 0));
    table.addColumn(new SQLColumn(table, "four", Types.INTEGER, 10, 0));
    table.addColumn(new SQLColumn(table, "five", Types.INTEGER, 10, 0));
    table.addColumn(new SQLColumn(table, "six", Types.INTEGER, 10, 0));
    table.getPrimaryKeyIndex().addIndexColumn(table.getColumn(0));
    table.getPrimaryKeyIndex().addIndexColumn(table.getColumn(1));
    table.getPrimaryKeyIndex().addIndexColumn(table.getColumn(2));
    table.getColumn(0).setNullable(DatabaseMetaData.columnNullable);
    table.getColumn(0).setAutoIncrement(true);

    db.addTable(table);/*  w  w w.  j  a va 2s.  c  o m*/
}

From source file:gov.nih.nci.cabig.caaers.datamigrator.CaaersDataMigratorTemplate.java

@Transactional
public final void migrateData() {

    Integer statusCode = 0;/*from   ww w  . jav  a  2 s. co m*/

    //check the status_code
    String query = "SELECT STATUS_CODE, RUNDATE FROM caaers_bootstrap_log WHERE OPERATION_CODE = "
            + migratorId();

    List<Map<String, Object>> l = getJdbcTemplate().queryForList(query);
    boolean noDataFound = CollectionUtils.isEmpty(l);
    CaaersDataMigrationContext context = new CaaersDataMigrationContext(isOralceDB(), isPostgresDB());

    if (!noDataFound) {
        Map map = l.get(0);
        statusCode = ((Number) map.get("STATUS_CODE")).intValue();
        String ranDate = String.valueOf(map.get("RUNDATE"));

        //arleady ran this migration sucessfully ?
        if (statusCodeComplete.equals(statusCode)) {
            log.info(String.format("Skipping the processing as the migrator[%s] already ran on %s.",
                    new Object[] { getClass().getName(), ranDate }));
            return;
        }
    }

    //do the template steps
    try {

        beforeMigrate(context);
        migrate(context);
        afterMigrate(context);
        statusCode = statusCodeComplete;

        //update the bootstrap 
        if (noDataFound) {
            getJdbcTemplate().update(
                    "insert into caaers_bootstrap_log(id, operation_code, status_code, rundate) values(?,?,?, ?)",
                    new Object[] { migratorId(), migratorId(), statusCode, new Date() },
                    new int[] { Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.DATE });
        } else {
            getJdbcTemplate().update(
                    "update caaers_bootstrap_log set status_code = ? , rundate = ? where operation_code = ?",
                    new Object[] { statusCode, new Date(), migratorId() },
                    new int[] { Types.INTEGER, Types.DATE, Types.INTEGER });
        }

    } catch (Exception e) {
        log.error(String.format("Error while running the migrator %s", getClass().getName()), e);
    }

}

From source file:org.smigo.user.JdbcUserDao.java

@Override
public void updateUser(User u) {
    String sql = "UPDATE users SET username = ?, email = ?, termsofservice = ?, about = ?, locale = ? , displayname = ?, password = ? WHERE id = ?";
    Object[] args = { u.getUsername(), u.getEmail(), u.isTermsOfService(), u.getAbout(), u.getLocale(),
            u.getDisplayName(), u.getPassword(), u.getId() };
    int[] types = { Types.VARCHAR, Types.VARCHAR, Types.BOOLEAN, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.VARCHAR, Types.INTEGER };
    jdbcTemplate.update(sql, args, types);
}

From source file:lab.example.service.MessageListener.java

public void handleMessage(String message) {

    final ObjectMapper objectMapper = new ObjectMapper();
    final String sql = "insert into lot(id,number) values(?,?)";

    try {//  ww w  .  j  a va2  s  .  com
        JsonNode node = objectMapper.readValue(message, JsonNode.class);
        jdbcTemplate.update(sql, new Object[] { node.get("id"), node.get("number") },
                new int[] { Types.VARCHAR, Types.INTEGER });
        logger.info("[.] message accepted : " + message);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.streamsets.pipeline.stage.it.DecimalTypeIT.java

@Test
public void correctCases() throws Exception {
    executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(4, 2)) PARTITIONED BY (dt string) STORED AS AVRO");

    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(4, 2).build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("dec", Field.create(BigDecimal.valueOf(12.12)));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);//from www.j  a  v  a  2s . com

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("dec", Field.create(BigDecimal.valueOf(1.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 3));
    map.put("dec", Field.create(BigDecimal.valueOf(12.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 4));
    map.put("dec", Field.create(BigDecimal.valueOf(0.1)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 5));
    map.put("dec", Field.create(BigDecimal.valueOf(0.12)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.dec", Types.DECIMAL), new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12.12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(3, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(4, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(5, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.12), rs.getBigDecimal(2));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:net.sourceforge.msscodefactory.cfinternet.v2_1.CFInternetSybase.CFInternetSybaseClusterTable.java

public int nextSecAppIdGen(CFInternetAuthorization Authorization, CFInternetClusterPKey PKey) {
    final String S_ProcName = "nextSecAppIdGen";
    if (!schema.isTransactionOpen()) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Not in a transaction");
    }//from ww w. jav a  2 s .c o m
    Connection cnx = schema.getCnx();
    long Id = PKey.getRequiredId();

    CallableStatement stmtSelectNextSecAppIdGen = null;
    try {
        String sql = "{ call sp_next_secappidgen( ?" + ", " + "?" + " ) }";
        stmtSelectNextSecAppIdGen = cnx.prepareCall(sql);
        int argIdx = 1;
        stmtSelectNextSecAppIdGen.registerOutParameter(argIdx++, java.sql.Types.INTEGER);
        stmtSelectNextSecAppIdGen.setLong(argIdx++, Id);
        stmtSelectNextSecAppIdGen.execute();
        int nextId = stmtSelectNextSecAppIdGen.getInt(1);
        return (nextId);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (stmtSelectNextSecAppIdGen != null) {
            try {
                stmtSelectNextSecAppIdGen.close();
            } catch (SQLException e) {
            }
            stmtSelectNextSecAppIdGen = null;
        }
    }
}

From source file:com.google.visualization.datasource.util.SqlDataSourceHelperTest.java

/**
 * Sets the information of the table columns: labels and types. Creates empty
 * list for the table rows as well.//from  www  . j  av  a2 s.  c  o  m
 *
 * This method is called before a test is executed.
 */
@Override
protected void setUp() {
    labels = Lists.newArrayList("ID", "Fname", "Lname", "Gender", "Salary", "IsMarried", "StartDate",
            "TimeStamp", "Time");
    // Use the JDBC type constants as defined in java.sql.Types.
    types = Lists.newArrayList(Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.CHAR, Types.INTEGER,
            Types.BOOLEAN, Types.DATE, Types.TIMESTAMP, Types.TIME);
    rows = Lists.newArrayList();
}

From source file:architecture.ee.web.community.profile.dao.jdbc.JdbcProfileDao.java

public void addProfileImage(ProfileImage image, File file) {
    try {// w  w  w  .  ja  v a2 s.c o m
        ProfileImage toUse = image;
        if (toUse.getProfileImageId() < 1L) {
            long imageId = getNextId(sequencerName);
            if (image instanceof DefaultProfileImage) {
                DefaultProfileImage impl = (DefaultProfileImage) toUse;
                impl.setProfileImageId(imageId);
            }
        } else {
            Date now = Calendar.getInstance().getTime();
            toUse.setModifiedDate(now);
        }

        if (toUse.getImageSize() == 0)
            toUse.setImageSize((int) FileUtils.sizeOf(file));
        getExtendedJdbcTemplate().update(
                getBoundSql("ARCHITECTURE_COMMUNITY.RESET_PROFILE_IMAGE_BY_USER").getSql(),
                new SqlParameterValue(Types.INTEGER, toUse.getUserId()));
        getExtendedJdbcTemplate().update(getBoundSql("ARCHITECTURE_COMMUNITY.INSERT_PROFILE_IMAGE").getSql(),
                new SqlParameterValue(Types.NUMERIC, toUse.getProfileImageId()),
                new SqlParameterValue(Types.INTEGER, toUse.getUserId()),
                new SqlParameterValue(Types.VARCHAR, toUse.getFilename()),
                new SqlParameterValue(Types.INTEGER, toUse.getImageSize()),
                new SqlParameterValue(Types.VARCHAR, toUse.getImageContentType()),
                new SqlParameterValue(Types.TIMESTAMP, toUse.getCreationDate()),
                new SqlParameterValue(Types.TIMESTAMP, toUse.getModifiedDate()));
        updateProfileImageImputStream(image, FileUtils.openInputStream(file));

    } catch (IOException e) {
    }
}

From source file:konditer_reorganized_database.dao.ReorganizedDatabase.java

public void settings() throws SQLException {
    String SQL_QUERY = "SELECT * FROM dmroy_kcake.settings";
    String page, title, meta_d, meta_k, text;
    int pageMetadatas = 0, pageMetadatas_1 = 0, sitePages = 0, sitePages_1 = 0;
    List<Map<String, Object>> rows = jdbcTemplate.queryForList(SQL_QUERY);
    for (Map<String, Object> row : rows) {
        page = (String) row.get("page");
        title = (String) row.get("title");
        meta_d = (String) row.get("meta_d");
        meta_k = (String) row.get("meta_k");
        text = (String) row.get("text");

        String SQL_QUERY_1 = "INSERT INTO cake_portal.page_metadatas (META_ID, META_KEYWORDS, META_DESCRIPTION) "
                + "VALUES ( ?, ?, ? ) ";
        int metaId = genIdDao.getPageMetadataId();
        pageMetadatas_1 = jdbcTemplate.update(SQL_QUERY_1, new Object[] { metaId, meta_k, meta_d });
        pageMetadatas += pageMetadatas_1;

        String SQL_QUERY_2 = "INSERT INTO cake_portal.site_pages (PAGE_ID, META_ID, PAGE_NAME, PAGE_TITLE, PAGE_CONTENT) "
                + "VALUES ( ?, ?, ?, ?, ? ) ";
        int pageId = genIdDao.getSitePageId();
        sitePages_1 = jdbcTemplate.update(SQL_QUERY_2, new Object[] { pageId, metaId, page, title, text },
                new int[] { Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });

        sitePages += sitePages_1;/*w ww  .jav  a  2s .  c  om*/
    }

    System.out.println("  page_metadatas  " + pageMetadatas + " ?.");
    System.out.println("  site_pages  " + sitePages + " ?.");
}