Example usage for java.sql PreparedStatement setObject

List of usage examples for java.sql PreparedStatement setObject

Introduction

In this page you can find the example usage for java.sql PreparedStatement setObject.

Prototype

default void setObject(int parameterIndex, Object x, SQLType targetSqlType) throws SQLException 

Source Link

Document

Sets the value of the designated parameter with the given object.

Usage

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

/**
 * stmt???????/*from  ww  w . j  a va2s . co  m*/
 * @param stmt I/O
 * @param parameterIndex parameter index
 * @param value set value
 * @param sqlType sql type
 * @throws SQLException error
 */
public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType)
        throws SQLException {
    if (sqlType == UN_USABLE_TYPE) {
        stmt.setNull(parameterIndex, Types.NULL);
    } else if (StringUtil.isBlank(value) || "".equals(value)) {
        stmt.setNull(parameterIndex, sqlType);
    } else {
        stmt.setObject(parameterIndex, value, sqlType);
    }
}

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

@Override
public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType)
        throws SQLException {
    if (sqlType == UN_USABLE_TYPE) {
        stmt.setNull(parameterIndex, Types.NULL);
    } else if (StringUtil.isBlank(value) || "".equals(value)) {
        stmt.setNull(parameterIndex, sqlType);
    } else if (sqlType == Types.TIMESTAMP) {
        stmt.setTimestamp(parameterIndex, Timestamp.valueOf(value));
    } else {/*from   w ww  .  j  a  va  2  s  . co  m*/
        stmt.setObject(parameterIndex, value, sqlType);
    }
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

/**
 * Test the {@code Set} object in Cassandra.
 *///from w  w w . j  av a2 s . c o m
@Test
public void testObjectSet() throws Exception {
    Statement stmt = con.createStatement();

    // Create the target Column family
    String createCF = "CREATE COLUMNFAMILY t65 (key text PRIMARY KEY," + "int1 int, " + "int2 int, "
            + "intset  set<int> " + ") ;";

    stmt.execute(createCF);
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    Statement statement = con.createStatement();
    String insert = "INSERT INTO t65 (key, int1,int2,intset) VALUES ('key1',1,100,{10,20,30,40});";
    statement.executeUpdate(insert);

    ResultSet result = statement.executeQuery("SELECT intset FROM t65 where key = 'key1';");

    // read the Set of Integer back out again
    Object rsObject = result.getObject(1);
    assertNotNull("Object Should Exist", rsObject);
    assertTrue("Object Should be Set", (rsObject instanceof Set));

    int sum = 0;

    // sum up the set - it should be 100
    for (Object rsEntry : ((Set) rsObject).toArray()) {
        assertTrue("Entry should be Integer", (rsEntry instanceof Integer));
        sum += ((Integer) rsEntry).intValue();
    }

    assertEquals("Total Should be 100", 100, sum);

    //System.out.println(resultToDisplay(result,65, "with set = {10,20,30,40}"));

    String update = "UPDATE t65 SET intset=? WHERE key=?;";

    PreparedStatement pstatement = con.prepareStatement(update);
    Set<Integer> mySet = new HashSet<Integer>();
    pstatement.setObject(1, mySet, Types.OTHER);
    pstatement.setString(2, "key1");

    pstatement.executeUpdate();

    result = statement.executeQuery("SELECT * FROM t65;");

    System.out.println(resultToDisplay(result, 65, " with set = <empty>"));

}

From source file:org.apache.phoenix.hive.mapreduce.PhoenixResultWritable.java

@Override
public void write(PreparedStatement statement) throws SQLException {
    ColumnInfo columnInfo = null;/*from   ww  w. jav a 2s .c  om*/
    Object value = null;

    try {
        for (int i = 0, limit = columnMetadataList.size(); i < limit; i++) {
            columnInfo = columnMetadataList.get(i);

            if (valueList.size() > i) {
                value = valueList.get(i);
            } else {
                value = null;
            }

            if (value == null) {
                statement.setNull(i + 1, columnInfo.getSqlType());
            } else {
                statement.setObject(i + 1, value, columnInfo.getSqlType());
            }
        }
    } catch (SQLException | RuntimeException e) {
        LOG.error("[column-info, value] : " + columnInfo + ", " + value);
        throw e;
    }
}

From source file:org.apache.phoenix.hive.mapreduce.PhoenixResultWritable.java

public void delete(PreparedStatement statement) throws SQLException {
    ColumnInfo columnInfo = null;//from   w  ww . j  a v  a2 s  . c om
    Object value = null;

    try {
        for (int i = 0, limit = primaryKeyColumnList.size(); i < limit; i++) {
            columnInfo = columnMetadataList.get(i);

            if (valueList.size() > i) {
                value = valueList.get(i);
            } else {
                value = null;
            }

            if (value == null) {
                statement.setNull(i + 1, columnInfo.getSqlType());
            } else {
                statement.setObject(i + 1, value, columnInfo.getSqlType());
            }
        }
    } catch (SQLException | RuntimeException e) {
        LOG.error("[column-info, value] : " + columnInfo + ", " + value);
        throw e;
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectSQLServer.java

@Override
public void setId(PreparedStatement ps, int index, Serializable value) throws SQLException {
    switch (idType) {
    case VARCHAR:
        ps.setObject(index, value, Types.VARCHAR);
        break;//w  ww  .  j  a  va  2s  .com
    case SEQUENCE:
        setIdLong(ps, index, value);
        break;
    }
}

From source file:org.apache.ode.scheduler.simple.jdbc.SchedulerDAOConnectionImpl.java

public boolean insertJob(JobDAO job, String nodeId, boolean loaded) throws DatabaseException {
    if (__log.isDebugEnabled())
        __log.debug("insertJob " + job.getJobId() + " on node " + nodeId + " loaded=" + loaded);

    Connection con = null;// w  ww . j  a va 2  s  . c o  m
    PreparedStatement ps = null;
    try {
        int i = 1;
        con = getConnection();
        ps = con.prepareStatement(SAVE_JOB);
        ps.setString(i++, job.getJobId());
        ps.setString(i++, nodeId);
        ps.setLong(i++, job.getScheduledDate());
        ps.setBoolean(i++, loaded);
        ps.setBoolean(i++, job.isTransacted());

        JobDetails details = job.getDetails();

        ps.setObject(i++, details.instanceId, Types.BIGINT);
        ps.setObject(i++, details.mexId, Types.VARCHAR);
        ps.setObject(i++, details.processId, Types.VARCHAR);
        ps.setObject(i++, details.type, Types.VARCHAR);
        ps.setObject(i++, details.channel, Types.VARCHAR);
        ps.setObject(i++, details.correlatorId, Types.VARCHAR);
        ps.setObject(i++, details.correlationKeySet, Types.VARCHAR);
        ps.setObject(i++, details.retryCount, Types.INTEGER);
        ps.setObject(i++, details.inMem, Types.BOOLEAN);

        if (details.detailsExt == null || details.detailsExt.size() == 0) {
            ps.setObject(i++, null, Types.BLOB);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                StreamUtils.write(bos, (Serializable) details.detailsExt);
            } catch (Exception ex) {
                __log.error("Error serializing job detail: " + job.getDetails());
                throw new DatabaseException(ex);
            }
            ps.setObject(i++, bos.toByteArray(), Types.BLOB);
        }

        return ps.executeUpdate() == 1;
    } catch (SQLException se) {
        throw new DatabaseException(se);
    } finally {
        close(ps);
        close(con);
    }
}

From source file:org.apache.ode.scheduler.simple.JdbcDelegate.java

public boolean insertJob(Job job, String nodeId, boolean loaded) throws DatabaseException {
    if (__log.isDebugEnabled())
        __log.debug("insertJob " + job.jobId + " on node " + nodeId + " loaded=" + loaded);

    Connection con = null;//from ww  w  .  j  a  v a  2s . c o m
    PreparedStatement ps = null;
    try {
        int i = 1;
        con = getConnection();
        ps = con.prepareStatement(SAVE_JOB);
        ps.setString(i++, job.jobId);
        ps.setString(i++, nodeId);
        ps.setLong(i++, job.schedDate);
        ps.setInt(i++, asInteger(loaded));
        ps.setInt(i++, asInteger(job.transacted));

        JobDetails details = job.detail;
        ps.setObject(i++, details.instanceId, Types.BIGINT);
        ps.setObject(i++, details.mexId, Types.VARCHAR);
        ps.setObject(i++, details.processId, Types.VARCHAR);
        ps.setObject(i++, details.type, Types.VARCHAR);
        ps.setObject(i++, details.channel, Types.VARCHAR);
        ps.setObject(i++, details.correlatorId, Types.VARCHAR);
        ps.setObject(i++, details.correlationKeySet, Types.VARCHAR);
        ps.setObject(i++, details.retryCount, Types.INTEGER);
        ps.setObject(i++, details.inMem, Types.INTEGER);

        if (details.detailsExt == null || details.detailsExt.size() == 0) {
            ps.setObject(i++, null, Types.BLOB);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                StreamUtils.write(bos, (Serializable) details.detailsExt);
            } catch (Exception ex) {
                __log.error("Error serializing job detail: " + job.detail);
                throw new DatabaseException(ex);
            }
            ps.setBytes(i++, bos.toByteArray());
        }

        return ps.executeUpdate() == 1;
    } catch (SQLException se) {
        throw new DatabaseException(se);
    } finally {
        close(ps);
        close(con);
    }
}

From source file:org.apache.openjpa.jdbc.sql.PostgresDictionary.java

/**
 * If column is an XML column, PostgreSQL requires that its value is set
 * by using {@link PreparedStatement#setObject(int, Object, int)}
 * with {@link Types#OTHER} as the third argument.
 *///ww w  . j av a 2 s. c om
public void setClobString(PreparedStatement stmnt, int idx, String val, Column col) throws SQLException {
    if (col != null && col.isXML())
        stmnt.setObject(idx, val, Types.OTHER);
    else
        super.setClobString(stmnt, idx, val, col);
}

From source file:org.apache.sqoop.hcat.HCatalogTestUtils.java

private void loadSqlTable(Connection conn, String table, int count, ColumnGenerator... extraCols)
        throws Exception {
    PreparedStatement statement = conn.prepareStatement(getSqlInsertTableStatement(table, extraCols),
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    try {/*from  w  w  w  .j  ava 2 s . co m*/
        for (int i = 0; i < count; ++i) {
            statement.setObject(1, i, Types.INTEGER);
            statement.setObject(2, "textfield" + i, Types.VARCHAR);
            for (int j = 0; j < extraCols.length; ++j) {
                statement.setObject(j + 3, extraCols[j].getDBValue(i), extraCols[j].getSqlType());
            }
            statement.executeUpdate();
        }
        if (!conn.getAutoCommit()) {
            conn.commit();
        }
    } finally {
        statement.close();
    }
}