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:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public void save(Penalty penalty) {
    String sql;//from w w w .j  a  va2  s .co m
    if (penalty.getKey() == null) {
        sql = "insert into penalty (playerid, adminid, type, reason, duration, synced, active, created, updated, expires) values (?,?,?,?,?,?,?,?,?,?)";
    } else {
        sql = "update penalty set playerid = ?," + "adminid = ?," + "type = ?," + "reason = ?,"
                + "duration = ?," + "synced = ?," + "active = ?," + "created = ?," + "updated = ?,"
                + "expires = ? where id = ? limit 1";
    }
    Connection conn = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        st.setLong(1, penalty.getPlayer());
        if (penalty.getAdmin() != null)
            st.setLong(2, penalty.getAdmin());
        else
            st.setNull(2, Types.INTEGER);
        st.setInt(3, penalty.getType().intValue());
        if (penalty.getReason() != null)
            st.setString(4, penalty.getReason());
        else
            st.setNull(4, Types.VARCHAR);
        if (penalty.getDuration() == null)
            penalty.setDuration(0L);
        st.setLong(5, penalty.getDuration());
        st.setBoolean(6, penalty.getSynced());
        st.setBoolean(7, penalty.getActive());
        if (penalty.getCreated() == null)
            penalty.setCreated(new Date());
        if (penalty.getUpdated() == null)
            penalty.setUpdated(new Date());
        st.setTimestamp(8, new java.sql.Timestamp(penalty.getCreated().getTime()));
        st.setTimestamp(9, new java.sql.Timestamp(penalty.getUpdated().getTime()));
        st.setTimestamp(10, new java.sql.Timestamp(
                DateUtils.addMinutes(penalty.getCreated(), penalty.getDuration().intValue()).getTime()));
        if (penalty.getKey() != null)
            st.setLong(11, penalty.getKey());
        st.executeUpdate();
        if (penalty.getKey() == null) {
            ResultSet rs = st.getGeneratedKeys();
            if (rs != null && rs.next()) {
                penalty.setKey(rs.getLong(1));
            } else {
                logger.warn("Couldn't get id for penalty player id {}", penalty.getPlayer());
            }
        }
    } catch (SQLException e) {
        logger.error("Save: {}", e);
    } catch (IOException e) {
        logger.error("Save: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.draagon.meta.manager.db.driver.MSSQLDriver.java

/**
 * Creates a table in the database/*w ww  .  j  a v  a2  s.  c  om*/
 */
@Override
public void createTable(Connection c, TableDef table) throws SQLException {
    String query = "CREATE TABLE [" + table + "] (\n";

    boolean multi = (table.getPrimaryKeys().size() > 1);

    boolean hasIdentity = false;

    // Create the individual table fields
    int found = 0;
    for (ColumnDef col : table.getColumns()) {
        String name = col.getName();
        if (name == null || name.length() == 0) {
            throw new IllegalArgumentException("No name defined for column [" + col + "]");
        }

        if (found > 0)
            query += ",\n";
        found++;

        String flags = "";
        if (col.isPrimaryKey() && !multi)
            flags = "PRIMARY KEY ";
        else if (col.isUnique())
            flags = "UNIQUE ";
        //else if (getManager().isIndex(mf)) flags = "NONCLUSTERED ";

        switch (col.getSQLType()) {
        case Types.BOOLEAN:
        case Types.BIT:
            query += "[" + name + "] [bit] " + flags;
            break;
        case Types.TINYINT:
            query += "[" + name + "] [tinyint] " + flags;
            break;
        case Types.SMALLINT:
            query += "[" + name + "] [smallint] " + flags;
            break;
        case Types.INTEGER:
            query += "[" + name + "] [int] " + flags;
            break;
        case Types.BIGINT:
            query += "[" + name + "] [bigint] " + flags;
            break;
        case Types.FLOAT:
            query += "[" + name + "] [float] " + flags;
            break;
        case Types.DOUBLE:
            query += "[" + name + "] [decimal](19,4) " + flags;
            break;
        case Types.TIMESTAMP:
            query += "[" + name + "] [datetime] " + flags;
            break;
        case Types.VARCHAR:
            query += "[" + name + "] [varchar](" + col.getLength() + ") " + flags;
            break;

        default:
            throw new IllegalArgumentException("Table [" + table + "] with Column [" + col
                    + "] is of SQL type (" + col.getSQLType() + ") which is not support by this database");
        }

        // Create the identity columns
        if (col.isAutoIncrementor()) {
            if (hasIdentity)
                throw new MetaException(
                        "Table [" + table + "] cannot have multiple identity (auto id) columns!");

            query += "NOT NULL IDENTITY( " + col.getSequence().getStart() + ", "
                    + col.getSequence().getIncrement() + " ) ";

            hasIdentity = true;
        }
    }

    query += "\n)";

    // This means there were no columns defined for the table
    if (found == 0)
        return;

    if (log.isDebugEnabled()) {
        log.debug("Creating table [" + table + "]: " + query);
    }
    //ystem.out.println( ">>>> Creating table [" + table + "]: " + query);

    Statement s = c.createStatement();
    try {
        s.execute(query);
    } finally {
        s.close();
    }
}

From source file:com.github.ferstl.spring.jdbc.oracle.OracleJdbcTemplateTest.java

@Test
public void withArgListAndArgTypes() {
    List<Object[]> batchArgs = Arrays.asList(new Object[] { "1" }, new Object[] { "2" }, new Object[] { "3" },
            new Object[] { "4" }, new Object[] { "5" }, new Object[] { "6" });

    int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.VARCHAR };/*from   w  w  w  .  j a  v a2s .  c  om*/

    int[] rowCounts = this.jdbcTemplate.batchUpdate("doesn't matter", batchArgs, argTypes);

    assertArrayEquals(rowCounts, new int[] { 0, 0, 0, 0, 5, 1 });
}

From source file:com.streamsets.pipeline.stage.destination.hive.queryexecutor.HiveQueryExecutorIT.java

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

    TargetRunner runner = new TargetRunner.Builder(HiveQueryDExecutor.class, queryExecutor)
            .setOnRecordError(OnRecordError.STOP_PIPELINE).build();
    runner.runInit();/*w w w.  ja v  a2  s. c o  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("default.el", new ImmutablePair("el.id", Types.INTEGER),
            new ImmutablePair("el.name", Types.VARCHAR));
}

From source file:org.snaker.engine.access.spring.SpringJdbcAccess.java

@Override
public void updateProcess(final Process process) {
    super.updateProcess(process);
    if (process.getBytes() != null) {
        template.execute(PROCESS_UPDATE_BLOB, new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
            @Override//from w  ww  .ja  va 2 s  .  c  o  m
            protected void setValues(PreparedStatement ps, LobCreator lobCreator)
                    throws SQLException, DataAccessException {
                try {
                    lobCreator.setBlobAsBytes(ps, 1, process.getBytes());
                    StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, process.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:org.jpos.ee.usertype.JsonType.java

/**
 * Write an instance of the mapped class to a prepared statement. Implementors
 * should handle possibility of null values. A multi-column type should be written
 * to parameters starting from <tt>index</tt>.
 *
 * @param st      a JDBC prepared statement
 * @param value   the object to write//from   ww  w  .  ja va 2 s. c  o m
 * @param index   statement parameter index
 * @param session
 * @throws HibernateException
 * @throws SQLException
 */
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
        throws HibernateException, SQLException {
    if (value == null) {
        st.setNull(index, Types.VARCHAR);
    } else {
        st.setString(index, value.toString());
    }
}

From source file:db.migration.V023__UpdateOrganisationToimipisteKoodi.java

public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
    LOG.info("migrate()...");

    // Get all organisations
    List<Map> resultSet = jdbcTemplate.query("SELECT * FROM organisaatio o", new RowMapper<Map>() {
        @Override/*from   ww w .  j  a  v  a2  s.  c o m*/
        public Map mapRow(ResultSet rs, int rowNum) throws SQLException {
            Map r = new HashMap<String, Object>();

            ResultSetMetaData metadata = rs.getMetaData();
            for (int i = 1; i <= metadata.getColumnCount(); i++) {
                String cname = metadata.getColumnName(i);
                int ctype = metadata.getColumnType(i);

                switch (ctype) {
                case Types.VARCHAR:
                    r.put(cname, rs.getString(cname));
                    break;

                default:
                    break;
                }
            }

            LOG.debug("  read from db : org = {}", r);

            _organisations.put((String) r.get("oid"), r);
            return r;
        }
    });

    // Generate and update initial values for toimipistekoodis
    for (Map org : resultSet) {
        if (isToimipiste(org, jdbcTemplate)) {
            String tpKoodi = calculateToimipisteKoodi(org, jdbcTemplate);
            updateToimipisteKoodi(org, tpKoodi, jdbcTemplate);
        }
    }

    LOG.info("  Processed {} organisations, updated {} Opetuspistes", _organisations.size(), _numUpdated);

    LOG.info("migrate()... done.");
}

From source file:konditer.client.dao.CustomerDao.java

@Override
public void addCustomer(int customerId, int discountId, String customerFirstName) {
    String SQL_QUERY = "INSERT INTO customers ( CUSTOMER_ID, " + "DISCOUNT_ID, " + "CUSTOMER_LAST_NAME, "
            + "CUSTOMER_FIRST_NAME, " + "CUSTOMER_PARENT_NAME, " + "CUSTOMER_DATE_BORN, " + "CUSTOMER_INFO ) "
            + "VALUES (?,?,?,?,?,?,?)";
    int rowCount = 0;
    try {/* ww  w.j  av  a  2 s  .  c o m*/
        rowCount = jdbcTemplate.update(SQL_QUERY,
                new Object[] { customerId, discountId, "", customerFirstName, "", new Date(), "" },
                new int[] { Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
                        Types.TIMESTAMP, Types.VARCHAR });
        Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE,
                " : {0} .",
                rowCount + "\n" + customerDao.getCustomer(customerId).toString());
    } catch (DataAccessException e) {
        rowCount = 0;
        Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE,
                "    .  ?: {0} .",
                rowCount);
    }
}

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);/* www.  j ava 2s .  co m*/

}

From source file:jp.co.tis.gsp.tools.dba.CsvInsertHandler.java

private int getTypeByName(String typeName) {
    Integer type = TYPE_NAMES.get(typeName);
    if (type == null) {
        return Types.VARCHAR;
    }/*from w  w  w  .j  av a 2 s. com*/
    return type;
}