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

void setObject(int parameterIndex, Object x) throws SQLException;

Source Link

Document

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

Usage

From source file:org.apache.phoenix.end2end.QueryMoreIT.java

private List<String> doQueryMore(String dataTableName, boolean dataTableMultiTenant, String tenantId,
        String tenantViewName, String[] cursorIds) throws Exception {
    Connection tenantConn = dataTableMultiTenant ? getTenantSpecificConnection(tenantId)
            : DriverManager.getConnection(getUrl());
    String tableName = dataTableMultiTenant ? tenantViewName : dataTableName;
    StringBuilder sb = new StringBuilder();
    String where = dataTableMultiTenant ? " WHERE (PARENT_ID, CREATED_DATE, ENTITY_HISTORY_ID) IN "
            : " WHERE (TENANT_ID, PARENT_ID, CREATED_DATE, ENTITY_HISTORY_ID) IN ";
    sb.append("SELECT ENTITY_HISTORY_ID FROM " + tableName + where);
    int numPkCols = dataTableMultiTenant ? 3 : 4;
    String query = addRvcInBinds(sb, cursorIds.length, numPkCols);
    PreparedStatement stmt = tenantConn.prepareStatement(query);
    int bindCounter = 1;
    for (int i = 0; i < cursorIds.length; i++) {
        Connection globalConn = DriverManager.getConnection(getUrl());
        Object[] pkParts = PhoenixRuntime.decodePK(globalConn, dataTableName, Base64.decode(cursorIds[i]));
        globalConn.close();//from  w  w w  .  ja  va2  s. c  o  m
        //start at index 1 to  ignore organizationId.
        int offset = dataTableMultiTenant ? 1 : 0;
        for (int j = offset; j < pkParts.length; j++) {
            stmt.setObject(bindCounter++, pkParts[j]);
        }
    }
    ResultSet rs = stmt.executeQuery();
    List<String> historyIds = new ArrayList<String>();
    while (rs.next()) {
        historyIds.add(rs.getString(1));
    }
    return historyIds;
}

From source file:com.geodetix.geo.dao.PostGisGeometryDAOImpl.java

/**
 * PostGIS implementation of the  //from   w w  w . j  ava2  s .co  m
 * {@link com.geodetix.geo.interfaces.GeometryLocalHome#findByPolygon(org.postgis.Polygon)}
 * method
 * 
 * @return a collection of bean's primary key beeing found.
 * @param polygon the {@link org.postgis.Polygon} to search in.
 * @throws javax.ejb.FinderException launched if an error occours during the search operation.
 */
public java.util.Collection findByPolygon(org.postgis.Polygon polygon) throws javax.ejb.FinderException {

    PreparedStatement pstm = null;
    Connection con = null;
    ResultSet result = null;

    try {

        con = this.dataSource.getConnection();

        pstm = con.prepareStatement(PostGisGeometryDAO.FIND_BY_POLYGON_STATEMENT);

        pstm.setObject(1, new PGgeometry(polygon));

        result = pstm.executeQuery();

        Vector keys = new Vector();

        while (result.next()) {
            keys.addElement(result.getObject("id"));
        }

        return keys;

    } catch (SQLException se) {
        throw new EJBException(se);

    } finally {
        try {
            if (result != null) {
                result.close();
            }
        } catch (Exception e) {
        }

        try {
            if (pstm != null) {
                pstm.close();
            }
        } catch (Exception e) {
        }

        try {
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testDate() throws SQLException {
    PreparedStatement prep = conn.prepareStatement("SELECT ?");
    Timestamp ts = Timestamp.valueOf("2001-02-03 04:05:06");
    prep.setObject(1, new java.util.Date(ts.getTime()));
    ResultSet rs = prep.executeQuery();
    rs.next();/*from www.  ja v a 2  s .c  o  m*/
    Timestamp ts2 = rs.getTimestamp(1);
    assertEquals(ts.toString(), ts2.toString());
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes a prepared INSERT/UPDATE statement on the database and returns the row count.
 * /*from   www .ja  v a2 s. c o m*/
 * @param expression
 *            The prepared statement to be executed.
 * @param parameters
 *            The parameters for the prepared statement.
 * @return A count of the number of updated rows.
 * @throws SQLException
 */
public int executeUpdate(String expression, List<Object> parameters) throws SQLException {
    PreparedStatement statement = null;

    try {
        statement = connection.prepareStatement(expression);
        logger.debug("executing prepared statement:\n" + expression);

        ListIterator<Object> iterator = parameters.listIterator();

        while (iterator.hasNext()) {
            int index = iterator.nextIndex() + 1;
            Object value = iterator.next();
            logger.debug("adding parameter: index=" + index + ", value=" + value);
            statement.setObject(index, value);
        }

        if (statement.execute()) {
            return -1;
        } else {
            return statement.getUpdateCount();
        }
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes a prepared query on the database and returns a CachedRowSet.
 * /* w  w w  .  ja  v a 2 s. c o m*/
 * @param expression
 *            The prepared statement to be executed.
 * @param parameters
 *            The parameters for the prepared statement.
 * @return The result of the query, as a CachedRowSet.
 * @throws SQLException
 */
public CachedRowSet executeCachedQuery(String expression, List<Object> parameters) throws SQLException {
    PreparedStatement statement = null;

    try {
        statement = connection.prepareStatement(expression);
        logger.debug("executing prepared statement:\n" + expression);

        ListIterator<Object> iterator = parameters.listIterator();

        while (iterator.hasNext()) {
            int index = iterator.nextIndex() + 1;
            Object value = iterator.next();
            logger.debug("adding parameter: index=" + index + ", value=" + value);
            statement.setObject(index, value);
        }

        ResultSet result = statement.executeQuery();
        CachedRowSet crs = new MirthCachedRowSet();
        crs.populate(result);
        DbUtils.closeQuietly(result);
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:org.globus.workspace.accounting.impls.dbdefault.DBAccountingPersistence.java

public synchronized void add(String uuid, int id, String ownerDN, long minutesRequested, Calendar creationTime,
        int CPUCores, int memory) throws WorkspaceDatabaseException {

    if (this.lager.accounting) {
        logger.trace("add(): uuid = '" + uuid + "', id = " + id + ", " + "ownerDN = '" + ownerDN
                + "', minutesRequest = " + minutesRequested + ", creationTime = "
                + creationTime.getTimeInMillis() + ", cpu cores = " + CPUCores + ", memory = " + memory);
    }/*  w w w  .  j a  v  a2s.c om*/

    Connection c = null;
    PreparedStatement pstmt = null;
    try {
        c = getConnection();
        pstmt = c.prepareStatement(SQL_INSERT_DEPLOYMENT);

        pstmt.setString(1, uuid);
        pstmt.setInt(2, id);
        pstmt.setString(3, ownerDN);
        pstmt.setObject(4, new Long(creationTime.getTimeInMillis()));
        pstmt.setObject(5, new Long(minutesRequested));
        pstmt.setInt(6, 1);
        pstmt.setNull(7, Types.INTEGER);
        pstmt.setInt(8, CPUCores);
        pstmt.setInt(9, memory);

        int inserted = pstmt.executeUpdate();
        if (this.lager.accounting) {
            logger.trace(Lager.id(id) + ": inserted " + inserted + " rows");
        }

    } catch (SQLException e) {
        logger.error("", e);
        throw new WorkspaceDatabaseException(e);
    } finally {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
            if (c != null) {
                returnConnection(c);
            }
        } catch (SQLException sql) {
            logger.error("SQLException in finally cleanup", sql);
        }
    }

    if (this.lager.accounting) {
        logger.trace(Lager.id(id) + ": add() done (uuid: " + uuid + ")");
    }

}

From source file:net.duckling.ddl.service.resource.dao.ResourceDAOImpl.java

@Override
public int updateMarkedUserSet(final List<Resource> resList) {
    this.getJdbcTemplate().batchUpdate(UPDATE_USER_SET, new BatchPreparedStatementSetter() {

        @Override/*from ww  w. ja va 2 s  .c  om*/
        public int getBatchSize() {
            return (null == resList || resList.isEmpty()) ? 0 : resList.size();
        }

        @Override
        public void setValues(PreparedStatement ps, int index) throws SQLException {
            Resource res = resList.get(index);
            int i = 0;
            ps.setObject(++i, res.getMarkedUserSet());
            ps.setInt(++i, res.getRid());
        }

    });
    return 1;
}

From source file:com.ibm.research.rdf.store.jena.impl.DB2ResultSetImpl.java

public Binding nextBinding() {
    DB2Binding binding = new DB2Binding(null);
    nextCalled = true;//from w w w . j a  v a 2s  .c  o  m
    if (!hasNextCalled) {
        hasNext();
    }
    hasNextCalled = false;
    if (hasNext) {
        Map<TypedValue, String> sidMap = new HashMap<TypedValue, String>();
        try {
            for (int i = 0; i < varList.size(); i++) {
                String colName = varList.get(i);
                String result = null;

                // result = set.getString(colName.toLowerCase());
                result = set.getString(colName);

                if (result != null) {
                    if (result.startsWith(Constants.PREFIX_SHORT_STRING)) {
                        if (liRs.isLiteralVariable(colName)) {
                            short type = TypeMap.SIMPLE_LITERAL_ID;
                            if (columnNames.contains(
                                    (colName + Constants.TYP_COLUMN_SUFFIX_IN_SPARQL_RS).toLowerCase())) {
                                type = set.getShort(
                                        (colName + Constants.TYP_COLUMN_SUFFIX_IN_SPARQL_RS).toLowerCase());
                            }
                            sidMap.put(new TypedValue(result, type), colName);

                        } else {
                            // this is a IRI
                            sidMap.put(new TypedValue(result, TypeMap.IRI_ID), colName);
                        }
                    } else {

                        RDFNode n = null;
                        if (liRs.isLiteralVariable(colName)) {

                            short type = TypeMap.SIMPLE_LITERAL_ID;
                            if (columnNames.contains(
                                    (colName + Constants.TYP_COLUMN_SUFFIX_IN_SPARQL_RS).toLowerCase())) {
                                type = set.getShort(
                                        (colName + Constants.TYP_COLUMN_SUFFIX_IN_SPARQL_RS).toLowerCase());
                            }

                            n = new String2Node(Constants.NAME_COLUMN_OBJECT, result, type).getNode();
                        } else {
                            n = new String2Node(Constants.NAME_COLUMN_SUBJECT, result).getNode();

                        }

                        binding.add(Var.alloc(colName), (n != null) ? n.asNode() : null);
                    }
                }
            }

            if (sidMap.size() > 0) {
                String sql = InsertAndUpdateStatements.getLongStringSelect(store.getLongStrings(),
                        sidMap.size());

                PreparedStatement sStmt = null;
                java.sql.ResultSet setSID = null;
                try {
                    sStmt = connection.prepareStatement(sql);

                    Iterator<TypedValue> sids = sidMap.keySet().iterator();
                    int i = 1;
                    while (sids.hasNext()) {
                        // mdb types
                        // sStmt.setObject(i, sids.next());
                        // i++;
                        TypedValue t = sids.next();
                        sStmt.setObject(i++, t.getValue());
                        sStmt.setObject(i++, t.getType());
                    }
                    setSID = sStmt.executeQuery();
                    while (setSID.next()) {
                        String sid = setSID.getString(Constants.NAME_COLUMN_SHORT_STRING.toLowerCase());
                        short type = setSID.getShort(Constants.NAME_COLUMN_PREFIX_TYPE.toLowerCase());

                        RDFNode n = new String2Node(Constants.NAME_COLUMN_OBJECT,
                                setSID.getString(Constants.NAME_COLUMN_LONG_STRING.toLowerCase()) + setSID
                                        .getString(Constants.NAME_COLUMN_LONG_STRING_OVERFLOW.toLowerCase()),
                                type).getNode();

                        binding.add(Var.alloc(sidMap.get(new TypedValue(sid, type))), n.asNode());
                    }
                } finally {
                    DB2CloseObjects.close(setSID, sStmt);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return binding;
}

From source file:com.alfaariss.oa.authentication.remote.aselect.idp.storage.jdbc.IDPJDBCStorage.java

/**
 * @see com.alfaariss.oa.engine.core.idp.storage.IIDPStorage#getIDP(java.lang.Object, java.lang.String)
 *//* www . j  a  va  2  s . c  om*/
public IIDP getIDP(Object id, String type) throws OAException {
    Connection connection = null;
    PreparedStatement pSelect = null;
    ResultSet resultSet = null;
    ASelectIDP oASelectIDP = null;
    try {
        connection = _dataSource.getConnection();

        StringBuffer sbSelect = new StringBuffer(_querySelectAll);
        sbSelect.append(" AND ");
        sbSelect.append(type);
        sbSelect.append("=?");
        pSelect = connection.prepareStatement(sbSelect.toString());
        pSelect.setBoolean(1, true);
        pSelect.setObject(2, id);
        resultSet = pSelect.executeQuery();
        if (resultSet.next()) {
            oASelectIDP = new ASelectIDP(resultSet.getString(COLUMN_ID),
                    resultSet.getString(COLUMN_FRIENDLYNAME), resultSet.getString(COLUMN_SERVER_ID),
                    resultSet.getString(COLUMN_URL), resultSet.getInt(COLUMN_LEVEL),
                    resultSet.getBoolean(COLUMN_SIGNING), resultSet.getString(COLUMN_COUNTRY),
                    resultSet.getString(COLUMN_LANGUAGE), resultSet.getBoolean(COLUMN_ASYNCHRONOUS_LOGOUT),
                    resultSet.getBoolean(COLUMN_SYNCHRONOUS_LOGOUT),
                    resultSet.getBoolean(COLUMN_SEND_ARP_TARGET));
        }
    } catch (Exception e) {
        _logger.fatal("Internal error during retrieval of IDP with id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (pSelect != null)
                pSelect.close();
        } catch (Exception e) {
            _logger.error("Could not close select statement", e);
        }

        try {
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            _logger.error("Could not close connection", e);
        }
    }
    return oASelectIDP;
}

From source file:com.mechanicshop.service.SearchServiceImpl.java

@Override
public void editCar(Object[] args, String tableName, Integer no) {

    String sql = "UPDATE " + tableName + " SET Tag=?,Phone=?,Name=?,"
            + "Vehicle=?,LicensePlate=?,Vin=?,InShop=?,OutShop=?,Status=?,Mileage=?,Picked=?,Payment=?,"
            + "Remarks=?,Rebuilder=?,Installer=?,FirstCheckBy=?,SecondCheckBy=?,FirstCheckDate=?,"
            + "SecondCheckDate=?,Media=?,Media2=?,ReferedBy=?,WarrantyLimit=?,Warranty=?,SMS=?,Comeback=? WHERE No = ?";

    Connection conn = null;/*w w  w. java 2 s .  c o  m*/

    try {
        conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(args.length + 1, no);
        for (int i = 0; i < args.length; i++) {
            Object object = args[i];
            if (object instanceof String) {
                String stringRepresentation = (String) object;
                if (stringRepresentation.isEmpty())
                    object = null;
            }

            ps.setObject(i + 1, object);
        }
        ps.executeUpdate();
        String status = (String) args[8];
        if (!tableName.contains(status.toLowerCase())) {
            String sqlDelete = "DELETE FROM " + tableName + " WHERE No = ?";
            ps = conn.prepareStatement(sqlDelete);
            ps.setInt(1, no);
            ps.executeUpdate();
        }
        ps.close();

    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}