Example usage for java.sql Types VARCHAR

List of usage examples for java.sql Types VARCHAR

Introduction

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

Prototype

int VARCHAR

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

Click Source Link

Document

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

Usage

From source file:com.sangupta.fileanalysis.db.DBResultViewer.java

/**
 * View resutls of a {@link ResultSet}.//from w  ww  .  j a  v a  2 s  . c  om
 * 
 * @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:com.adaptris.core.services.jdbc.types.StringColumnTranslatorTest.java

@Test
public void testStringWrite() throws Exception {
    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", "SomeData", Types.VARCHAR);
    StringWriter writer = new StringWriter();
    try (OutputStream out = new WriterOutputStream(writer)) {
        translator.write(row, 0, out);/*ww  w  .j  a  v a 2 s .  co m*/
    }
    String translated = writer.toString();
    assertEquals("SomeData", translated);
}

From source file:net.navasoft.madcoin.backend.services.security.ProviderDataAccess.java

/**
 * Load user by username.//w ww .j  av  a2s.c o  m
 * 
 * @param username
 *            the username
 * @return the user details
 * @throws UsernameNotFoundException
 *             the username not found exception
 * @throws DataAccessException
 *             the data access exception
 * @throws BadConfigException
 *             the bad config exception
 * @since 31/08/2014, 07:23:59 PM
 */
@Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException, BadConfigException {
    String key = defineKey(username);
    if (initializer.containsKey(key)) {
        try {
            mapping.addValue("username", username, Types.VARCHAR);
            User user = dao.queryForObject(initializer.getProperty(key), mapping, defineMapper(username));
            return user;
        } catch (DataAccessException dao) {
            if (dao instanceof EmptyResultDataAccessException) {
                throw new UsernameNotFoundException(dao.getMessage());
            } else {
                dao.printStackTrace();
                throw dao;
            }
        }
    } else {
        throw new BadConfigException("Query is not defined.");
    }
}

From source file:com.mtgi.analytics.sql.BehaviorTrackingDataSourceTest.java

@Test
public void testPreparedStatement() throws Exception {
    //test tracking through the prepared statement API, which should also
    //log parameters in the events.
    PreparedStatement stmt = conn.prepareStatement("insert into TEST_TRACKING values (?, ?, ?)");
    stmt.setLong(1, 1);//from   www .  j a  v a 2s. co m
    stmt.setString(2, "hello");
    stmt.setObject(3, null, Types.VARCHAR);
    assertEquals(1, stmt.executeUpdate());

    //test support for batching.  each batch should log 1 event.
    stmt.setLong(1, 3);
    stmt.setString(2, "batch");
    stmt.setObject(3, "1", Types.VARCHAR);
    stmt.addBatch();

    stmt.setLong(1, 4);
    stmt.setString(2, "batch");
    stmt.setObject(3, "2", Types.VARCHAR);
    stmt.addBatch();
    stmt.executeBatch();

    //back to a regular old update.
    stmt.setLong(1, 2);
    stmt.setObject(2, "goodbye", Types.VARCHAR);
    stmt.setNull(3, Types.VARCHAR);
    assertEquals(1, stmt.executeUpdate());

    stmt = conn.prepareStatement("update TEST_TRACKING set DESCRIPTION = 'world'");
    assertEquals(4, stmt.executeUpdate());

    stmt = conn.prepareStatement("select ID from TEST_TRACKING order by ID");
    ResultSet rs = stmt.executeQuery();
    int index = 0;
    long[] keys = { 1L, 2L, 3L, 4L };
    while (rs.next())
        assertEquals(keys[index++], rs.getLong(1));
    rs.close();
    assertEquals(4, index);

    manager.flush();
    assertEventDataMatches("BehaviorTrackingDataSourceTest.testPreparedStatement-result.xml");
}

From source file:dk.teachus.backend.dao.hibernate.PasswordUserType.java

public int[] sqlTypes() {
    return new int[] { Types.VARCHAR };
}

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  w  ww.  ja va 2 s  . c  om*/
 *
 * 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:com.vecna.dbDiff.builder.RelationalDatabaseBuilderTest.java

/**
 * Test {@link RelationalDatabaseBuilderImpl#createRelationalDatabase(CatalogSchema)).
 * @throws Exception//from  w w  w .j a v a 2s  . c  om
 */
public void testCreateRelationalDatabase() throws Exception {
    RelationalDatabase database = getDatabase();

    assertEquals("wrong number of tables", 2, database.getTables().size());

    RelationalTable personTable = database.getTableByName("PERSON");
    assertNotNull("table PERSON not found", personTable);

    List<Column> cols = new ArrayList<>(personTable.getColumns());
    assertEquals("wrong number of columns", 3, cols.size());
    assertEquals("wrong column", "ID", cols.get(0).getName());
    assertEquals("wrong column", Boolean.FALSE, cols.get(0).getIsNullable());
    assertEquals("wrong column", Types.BIGINT, cols.get(0).getType());

    assertEquals("wrong column", "NAME", cols.get(1).getName());
    assertEquals("wrong column", Boolean.FALSE, cols.get(1).getIsNullable());
    assertEquals("wrong column", Types.VARCHAR, cols.get(1).getType());

    assertEquals("wrong column", "DOB", cols.get(2).getName());
    assertEquals("wrong column", Boolean.FALSE, cols.get(2).getIsNullable());
    assertEquals("wrong column", Types.TIMESTAMP, cols.get(2).getType());

    assertEquals("wrong number PK columns", Arrays.asList("ID"), personTable.getPkColumns());

    assertEquals("wrong number of indices", 2, personTable.getIndices().size());

    RelationalIndex nameDOB = getIndex(personTable, "NAME", "DOB");
    assertEquals("NAME_DOB_IDX", nameDOB.getName());

    getIndex(personTable, "ID");

    RelationalTable joinTable = database.getTableByName("PERSON_RELATIVES");

    cols = new ArrayList<>(joinTable.getColumns());
    assertEquals("wrong number of columns", 3, cols.size());

    assertEquals("wrong column", "PERSON_ID", cols.get(0).getName());
    assertEquals("wrong column", Boolean.FALSE, cols.get(0).getIsNullable());
    assertEquals("wrong column", Types.BIGINT, cols.get(0).getType());

    assertEquals("wrong column", "RELATIVE_ID", cols.get(1).getName());
    assertEquals("wrong column", Boolean.FALSE, cols.get(1).getIsNullable());
    assertEquals("wrong column", Types.BIGINT, cols.get(1).getType());

    assertEquals("wrong column", "RELATIONSHIP", cols.get(2).getName());
    assertEquals("wrong column", Boolean.TRUE, cols.get(2).getIsNullable());
    assertEquals("wrong column", Types.VARCHAR, cols.get(2).getType());

    assertEquals("wrong PK columns", Arrays.asList("PERSON_ID", "RELATIVE_ID"), joinTable.getPkColumns());

    getIndex(joinTable, "PERSON_ID", "RELATIVE_ID");

    ForeignKey fkPerson = getForeignKey(joinTable, "FK_PERSON");
    assertEquals("PERSON_ID", fkPerson.getFkColumn());
    assertEquals("PERSON_RELATIVES", fkPerson.getFkTable());

    assertEquals("ID", fkPerson.getPkColumn());
    assertEquals("PERSON", fkPerson.getPkTable());

    ForeignKey fkRelative = getForeignKey(joinTable, "FK_RELATIVE");
    assertEquals("RELATIVE_ID", fkRelative.getFkColumn());
    assertEquals("PERSON_RELATIVES", fkRelative.getFkTable());

    assertEquals("ID", fkRelative.getPkColumn());
    assertEquals("PERSON", fkRelative.getPkTable());
}

From source file:nl.surfnet.coin.api.oauth.OpenConextOauth2JdbcTokenStore.java

@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    AuthorizationRequest authorizationRequest = authentication.getAuthorizationRequest();
    String clientId = authorizationRequest.getClientId();
    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
    if (!(clientDetails instanceof OpenConextClientDetails)) {
        throw new RuntimeException("The clientDetails is of the type '"
                + (clientDetails != null ? clientDetails.getClass() : "null")
                + "'. Required is a (sub)class of ExtendedBaseClientDetails");
    }//from  ww w .  ja v a 2  s  .co m

    ClientMetaData clientMetaData = ((OpenConextClientDetails) clientDetails).getClientMetaData();

    String refreshToken = null;
    if (token.getRefreshToken() != null) {
        refreshToken = token.getRefreshToken().getValue();
    }

    String value = extractTokenKey(token.getValue());
    jdbcTemplate.update(ACCESS_TOKEN_INSERT_STATEMENT,
            new Object[] { value, new SqlLobValue(SerializationUtils.serialize(token)),
                    authenticationKeyGenerator.extractKey(authentication),
                    authentication.isClientOnly() ? null : authentication.getName(),
                    authentication.getAuthorizationRequest().getClientId(), clientMetaData.getAppEntityId(),
                    new SqlLobValue(SerializationUtils.serialize(authentication)), refreshToken },
            new int[] { Types.VARCHAR, Types.BLOB, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
                    Types.BLOB, Types.VARCHAR });

}

From source file:Main.java

  public void readData(RowSetInternal caller) throws SQLException {
  System.out.println("--- CustomRowSetReader: begin. ---");
  if (caller == null) {
    System.out.println("CustomRowSetReader: caller is null.");
    return;//from  w  w  w.  j  av a2 s. co  m
  }

  CachedRowSet crs = (CachedRowSet) caller;
  // CachedRowSet crs = (CachedRowSet) caller.getOriginal();

  RowSetMetaData rsmd = new RowSetMetaDataImpl();

  rsmd.setColumnCount(3);

  rsmd.setColumnType(1, Types.VARCHAR);
  rsmd.setColumnType(2, Types.INTEGER);
  rsmd.setColumnType(3, Types.VARCHAR);

  rsmd.setColumnName(1, "col1");
  rsmd.setColumnName(2, "col2");
  rsmd.setColumnName(3, "col3");

  crs.setMetaData(rsmd);
  System.out.println("CustomRowSetReader: crs.setMetaData( rsmd );");

  crs.moveToInsertRow();

  crs.updateString(1, "StringCol11");
  crs.updateInt(2, 1);
  crs.updateString(3, "StringCol31");
  crs.insertRow();
  System.out.println("CustomRowSetReader: crs.insertRow() 1");

  crs.updateString(1, "StringCol12");
  crs.updateInt(2, 2);
  crs.updateString(3, "StringCol32");
  crs.insertRow();
  System.out.println("CustomRowSetReader: crs.insertRow() 2");

  crs.moveToCurrentRow();
  crs.beforeFirst();
  displayRowSet(crs);
  crs.beforeFirst();
  // crs.acceptChanges();
  System.out.println("CustomRowSetReader: end.");
}

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   w w w.j ava  2s  . c  o m

    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());
        }
    });
}