List of usage examples for java.sql PreparedStatement setObject
void setObject(int parameterIndex, Object x) throws SQLException;
Sets the value of the designated parameter using the given object.
From source file:com.wso2telco.dep.operatorservice.dao.OperatorDAO.java
public List<OperatorApplicationDTO> loadActiveApplicationOperators(OperatorAppSearchDTO searchDTO) throws SQLException, Exception { Connection con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB); PreparedStatement ps = null; ResultSet rs = null;/*w w w. jav a 2s.c o m*/ List<OperatorApplicationDTO> operators = new ArrayList(); try { if (con == null) { throw new Exception("Connection not found"); } StringBuilder queryString = new StringBuilder( "SELECT oa.id id, oe.api, oa.applicationid, oa.operatorid,") .append(" o.operatorname,o.refreshtoken, o.tokenvalidity, o.tokentime,") .append(" o.token, o.tokenurl, o.tokenauth,oe.operatorid ") .append(" FROM OPERATORAPPS oa, OPERATORS o ,ENDPOINTAPPS e, OPERATORENDPOINTS oe ") .append(" WHERE oa.operatorid = o.id ").append(" AND oa.applicationid=e.applicationid ") .append(" AND e.endpointid = oe.id ").append(" AND oe.id = e.endpointid ") .append(" AND e.isactive = 1 ").append(" AND oa.isactive = 1 "); List<Object> params = new ArrayList<Object>(); if (searchDTO.getApiName() != null && !searchDTO.getApiName().isEmpty()) { queryString.append(" AND oe.api =?"); params.add(searchDTO.getApiName().trim()); } if (searchDTO.getApplicationId() != 0) { queryString.append(" AND e.applicationid =?"); params.add(Integer.valueOf(searchDTO.getApplicationId())); } ps = con.prepareStatement(queryString.toString()); if (!params.isEmpty()) { Object[] paramArray = params.toArray(new Object[params.size()]); for (int x = 0; x < paramArray.length; x++) { ps.setObject(x + 1, paramArray[x]); //Since the param index start from 1 } } this.log.debug("sql query in getApplicationOperators : " + ps); rs = ps.executeQuery(); while (rs.next()) { OperatorApplicationDTO oper = new OperatorApplicationDTO(); oper.setId(rs.getInt("id")); oper.setApiName(rs.getString("api")); oper.setApplicationid(rs.getInt("applicationid")); oper.setOperatorid(rs.getInt("operatorid")); oper.setOperatorname(rs.getString("operatorname")); oper.setRefreshtoken(rs.getString("refreshtoken")); oper.setTokenvalidity(rs.getLong("tokenvalidity")); oper.setTokentime(rs.getLong("tokentime")); oper.setToken(rs.getString("token")); oper.setTokenurl(rs.getString("tokenurl")); oper.setTokenauth(rs.getString("tokenauth")); operators.add(oper); } } catch (SQLException e) { this.log.error("database operation error in getApplicationOperators : ", e); } catch (Exception e) { this.log.error("error in getApplicationOperators : ", e); } finally { DbUtils.closeAllConnections(ps, con, rs); } return operators; }
From source file:com.kylinolap.rest.service.QueryService.java
/** * @param preparedState/* ww w . ja v a2 s .co m*/ * @param param * @throws SQLException */ private void setParam(PreparedStatement preparedState, int index, StateParam param) throws SQLException { boolean isNull = (null == param.getValue()); Class<?> clazz = Object.class; try { clazz = Class.forName(param.getClassName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } Rep rep = Rep.of(clazz); switch (rep) { case PRIMITIVE_CHAR: case CHARACTER: case STRING: preparedState.setString(index, isNull ? null : String.valueOf(param.getValue())); break; case PRIMITIVE_INT: case INTEGER: preparedState.setInt(index, isNull ? null : Integer.valueOf(param.getValue())); break; case PRIMITIVE_SHORT: case SHORT: preparedState.setShort(index, isNull ? null : Short.valueOf(param.getValue())); break; case PRIMITIVE_LONG: case LONG: preparedState.setLong(index, isNull ? null : Long.valueOf(param.getValue())); break; case PRIMITIVE_FLOAT: case FLOAT: preparedState.setFloat(index, isNull ? null : Float.valueOf(param.getValue())); break; case PRIMITIVE_DOUBLE: case DOUBLE: preparedState.setDouble(index, isNull ? null : Double.valueOf(param.getValue())); break; case PRIMITIVE_BOOLEAN: case BOOLEAN: preparedState.setBoolean(index, isNull ? null : Boolean.parseBoolean(param.getValue())); break; case PRIMITIVE_BYTE: case BYTE: preparedState.setByte(index, isNull ? null : Byte.valueOf(param.getValue())); break; case JAVA_UTIL_DATE: case JAVA_SQL_DATE: preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue())); break; case JAVA_SQL_TIME: preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue())); break; case JAVA_SQL_TIMESTAMP: preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue())); break; default: preparedState.setObject(index, isNull ? null : param.getValue()); } }
From source file:org.netkernelroc.gradle.apposite.Package.java
public void install(Connection connection, File nkInstance) throws Exception { PackageVersion toInstall = versions.last(); File packageFile = toInstall.download(nkInstance, connection); File expandedPackage = NetKernelConvention.createTempDir(); NetKernelConvention.expandZip(packageFile, expandedPackage); Document manifestDocument = new Builder().build(new File(expandedPackage, "manifest.xml")); Nodes modulesNodes = manifestDocument.query("/manifest/module"); final String setInstalledSql = "UPDATE PACKAGE_VERSIONS SET INSTALLED=TRUE WHERE ID=?;"; final PreparedStatement setInstalledPS = connection.prepareStatement(setInstalledSql); final String addTransactionEventSql = "INSERT INTO PACKAGE_TRANSACTION_EVENTS VALUES (\n" + " NULL,\n" + " @TRANSACTIONID,\n" + " 1,\n" + " ?\n" + ");"; final PreparedStatement addTransactionEventPS = connection.prepareStatement(addTransactionEventSql); final String addModuleSql = "MERGE INTO MODULES (\n" + " PACKAGEVID,\n" + " IDENTITY,\n" + " VERSION,\n" + " LOCALSRC,\n" + " RUNLEVEL,\n" + " EXPANDED\n" + ")\n" + "KEY (IDENTITY, VERSION)\n" + "VALUES (\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?\n" + ");"; final PreparedStatement addModulePS = connection.prepareStatement(addModuleSql); setInstalledPS.clearParameters();/*from www .j a v a2 s . com*/ setInstalledPS.setLong(1, toInstall.getId()); setInstalledPS.executeUpdate(); addTransactionEventPS.clearParameters(); addTransactionEventPS.setLong(1, id); addTransactionEventPS.executeUpdate(); for (int moduleI = 0; moduleI < modulesNodes.size(); moduleI++) { Node moduleNode = modulesNodes.get(moduleI); String uri = moduleNode.query("uri").get(0).getValue(); String version = moduleNode.query("version").get(0).getValue(); int runLevel = Integer.parseInt(moduleNode.query("runlevel").get(0).getValue()); String source = moduleNode.query("source").get(0).getValue(); boolean expand = Boolean.parseBoolean(moduleNode.query("expand").get(0).getValue()); Integer[] versionArray = RepositorySet.stringArrayToIntArray(version.split("\\.")); File targetFile; if (uri.startsWith("urn:com:ten60:core:")) { expand = false; targetFile = new File(nkInstance, "lib"); } else { targetFile = new File(nkInstance, "modules"); } File moduleJar = new File(expandedPackage, source); String baseName = uri.replaceAll(":", ".") + "-" + version; File target; File jarTarget = new File(targetFile, baseName + ".jar"); File expandedTarget = new File(targetFile, baseName); if (expand) { target = expandedTarget; } else { target = jarTarget; } if (target.exists()) { System.out.println("Not moving module into place as it already exists"); } else { if (expand) { System.out.println("Expanding module " + uri + " to " + expandedTarget.getAbsolutePath()); NetKernelConvention.expandZip(moduleJar, expandedTarget); } else { System.out.println("Moving module " + uri + " to " + jarTarget.getAbsolutePath()); FileUtils.moveFile(moduleJar, jarTarget); } } addModulePS.clearParameters(); addModulePS.setLong(1, toInstall.getId()); addModulePS.setString(2, uri); addModulePS.setObject(3, versionArray); addModulePS.setString(4, nkInstance.toURI().relativize(target.toURI()).getPath()); addModulePS.setInt(5, runLevel); addModulePS.setBoolean(6, expand); addModulePS.executeUpdate(); } FileUtils.deleteDirectory(expandedPackage); latestInstalledVersion = toInstall; }
From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java
private void runDml(DML dmlType, List records, boolean useDeclaredOnly, List<String> includeFields) { PreparedStatement st = null; boolean inTrans = inTransaction(); int batchCount = 0; String command = null;//from w w w . jav a2 s . co m if (!inTrans) startTransaction(); try { Object obj = records.get(0); Class objClass = obj.getClass(); String schema = getEntitySchema(objClass); Boolean isCamelCased = useCamelCase(objClass); HashMap<Method, String> fieldMapping = getFieldMapping(objClass, GET, isCamelCased, useDeclaredOnly); HashMap<Integer, Method> indexMapping = new HashMap(); String tableName = getTableName(objClass); if (tableName == null) tableName = getDbName(isCamelCased, objClass.getSimpleName(), null); if (dmlType == DML.UPDATE) command = getUpdateCommand(tableName, schema, fieldMapping, indexMapping, includeFields); else if (dmlType == DML.INSERT) command = getInsertCommand(tableName, schema, fieldMapping, indexMapping); else command = getDeleteCommand(tableName, schema, fieldMapping, indexMapping); st = conn.prepareStatement(command); for (Object record : records) { for (int index : indexMapping.keySet()) { Object value = indexMapping.get(index).invoke(record, null); if (value instanceof java.util.Date) { value = new java.sql.Date(((java.util.Date) value).getTime()); } st.setObject((Integer) index, value); } if (useBatch == true) st.addBatch(); else st.executeUpdate(); if (useBatch == true && ++batchCount % batchSize == 0) { st.executeBatch(); } } if (useBatch == true) st.executeBatch(); //flush out remaining records if (!inTrans) commitTransaction(); } catch (Exception ex) { ex.printStackTrace(); if (!inTrans) rollbackTransaction(); throw new DataQueryException(command, "runDml", ex); } finally { if (st != null) { try { st.close(); } catch (Exception ex) { } } } }
From source file:org.nuxeo.ecm.core.storage.sql.Mapper.java
/** * Copy the rows from tableName with ids in fragmentIds into new ones with * new ids given by idMap.// w w w . ja v a 2s. co m * * @return {@link Boolean#TRUE} for a modification or creation, * {@link Boolean#FALSE} for a deletion, {@code null} otherwise * (still absent) * @throws SQLException */ protected Boolean copyFragments(String tableName, Set<Serializable> ids, Map<Serializable, Serializable> idMap, Serializable overwriteId) throws SQLException { String copySql = sqlInfo.getCopySql(tableName); Column copyIdColumn = sqlInfo.getCopyIdColumn(tableName); PreparedStatement copyPs = connection.prepareStatement(copySql); String deleteSql = sqlInfo.getDeleteSql(tableName); PreparedStatement deletePs = connection.prepareStatement(deleteSql); try { boolean before = false; boolean after = false; for (Serializable id : ids) { Serializable newId = idMap.get(id); boolean overwrite = newId.equals(overwriteId); if (overwrite) { // remove existing first if (isLogEnabled()) { logSQL(deleteSql, Collections.singletonList(newId)); } deletePs.setObject(1, newId); int delCount = deletePs.executeUpdate(); logCount(delCount); before = delCount > 0; } copyIdColumn.setToPreparedStatement(copyPs, 1, newId); copyIdColumn.setToPreparedStatement(copyPs, 2, id); if (isLogEnabled()) { logSQL(copySql, Arrays.asList(newId, id)); } int copyCount = copyPs.executeUpdate(); logCount(copyCount); if (overwrite) { after = copyCount > 0; } } // * , n -> mod (TRUE) // n , 0 -> del (FALSE) // 0 , 0 -> null return after ? Boolean.TRUE : (before ? Boolean.FALSE : null); } finally { closePreparedStatement(copyPs); closePreparedStatement(deletePs); } }
From source file:org.linqs.psl.database.rdbms.RDBMSInserter.java
private void insertInternal(List<Double> values, List<List<Object>> data) { assert (values.size() == data.size()); int partitionID = partition.getID(); if (partitionID < 0) { throw new IllegalArgumentException("Partition IDs must be non-negative."); }//w w w .ja v a 2s . c o m for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) { List<Object> row = data.get(rowIndex); assert (row != null); if (row.size() != predicateInfo.argumentColumns().size()) { throw new IllegalArgumentException( String.format("Data on row %d length does not match for %s: Expecting: %d, Got: %d", rowIndex, partition.getName(), predicateInfo.argumentColumns().size(), row.size())); } } try (Connection connection = dataStore.getConnection(); PreparedStatement multiInsertStatement = connection.prepareStatement(multiInsertSQL); PreparedStatement singleInsertStatement = connection.prepareStatement(singleInsertSQL);) { int batchSize = 0; // We will go from the multi-insert to the single-insert when we don't have enough data to fill the multi-insert. PreparedStatement activeStatement = multiInsertStatement; int insertSize = DEFAULT_MULTIROW_COUNT; int rowIndex = 0; while (rowIndex < data.size()) { // Index for the current index. int paramIndex = 1; if (activeStatement == multiInsertStatement && data.size() - rowIndex < DEFAULT_MULTIROW_COUNT) { // Commit any records left in the multi-insert batch. if (batchSize > 0) { activeStatement.executeBatch(); activeStatement.clearBatch(); batchSize = 0; } activeStatement = singleInsertStatement; insertSize = 1; } for (int i = 0; i < insertSize; i++) { List<Object> row = data.get(rowIndex); Double value = values.get(rowIndex); // Partition activeStatement.setInt(paramIndex++, partitionID); // Value if (value == null || value.isNaN()) { activeStatement.setNull(paramIndex++, java.sql.Types.DOUBLE); } else { activeStatement.setDouble(paramIndex++, value); } for (int argIndex = 0; argIndex < predicateInfo.argumentColumns().size(); argIndex++) { Object argValue = row.get(argIndex); assert (argValue != null); if (argValue instanceof Integer) { activeStatement.setInt(paramIndex++, (Integer) argValue); } else if (argValue instanceof Double) { // The standard JDBC way to insert NaN is using setNull if (Double.isNaN((Double) argValue)) { activeStatement.setNull(paramIndex++, java.sql.Types.DOUBLE); } else { activeStatement.setDouble(paramIndex++, (Double) argValue); } } else if (argValue instanceof String) { // This is the most common value we get when someone is using InsertUtils. // The value may need to be convered from a string. activeStatement.setObject(paramIndex++, convertString((String) argValue, argIndex)); } else if (argValue instanceof UniqueIntID) { activeStatement.setInt(paramIndex++, ((UniqueIntID) argValue).getID()); } else if (argValue instanceof UniqueStringID) { activeStatement.setString(paramIndex++, ((UniqueStringID) argValue).getID()); } else { throw new IllegalArgumentException("Unknown data type for :" + argValue); } } rowIndex++; } activeStatement.addBatch(); batchSize++; if (batchSize >= DEFAULT_PAGE_SIZE) { activeStatement.executeBatch(); activeStatement.clearBatch(); batchSize = 0; } } if (batchSize > 0) { activeStatement.executeBatch(); activeStatement.clearBatch(); batchSize = 0; } activeStatement.clearParameters(); activeStatement = null; } catch (SQLException ex) { log.error(ex.getMessage()); throw new RuntimeException("Error inserting into RDBMS.", ex); } }
From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java
private int fillEventStatement(PreparedStatement ps, Event ev, AccessToken at, int i) throws SQLException { int idx = i;/*w w w.jav a 2s. c o m*/ ps.setString(idx++, ev.getExtId().getExtId()); ps.setString(idx++, ev.getTimezoneName()); ps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VOPACITY, ev.getOpacity().toString())); ps.setString(idx++, ev.getTitle()); ps.setString(idx++, ev.getLocation()); Integer cat = catIdFromString(ps.getConnection(), ev.getCategory(), at.getDomain().getId()); if (cat != null) { ps.setInt(idx++, cat); } else { ps.setNull(idx++, Types.INTEGER); } ps.setInt(idx++, RFC2445.getPriorityOrDefault(ev.getPriority())); ps.setInt(idx++, ev.getPrivacy().toInteger()); if (ev.getStartDate() != null) { ps.setTimestamp(idx++, new Timestamp(ev.getStartDate().getTime())); } else { ps.setNull(idx++, Types.DATE); } ps.setInt(idx++, ev.getDuration()); ps.setBoolean(idx++, ev.isAllday()); EventRecurrence r = ev.getRecurrence(); ps.setString(idx++, r.getKind().toString()); ps.setInt(idx++, r.getFrequence()); ps.setString(idx++, new RecurrenceDaysSerializer().serialize(r.getDays())); if (r.getEnd() != null) { ps.setTimestamp(idx++, new Timestamp(r.getEnd().getTime())); } else { ps.setNull(idx++, Types.DATE); } ps.setNull(idx++, Types.VARCHAR); // color ps.setNull(idx++, Types.DATE); // FIXME completed ps.setNull(idx++, Types.VARCHAR); // FIXME url ps.setString(idx++, ev.getDescription()); ps.setInt(idx++, at.getDomain().getId()); ps.setString(idx++, at.getOrigin()); ps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VCOMPONENT, ev.getType().toString())); ps.setInt(idx++, ev.getSequence()); return idx; }
From source file:org.globus.workspace.accounting.impls.dbdefault.DBAccountingPersistence.java
public synchronized String end(int id, String ownerDN, long minutesElapsed) throws WorkspaceDatabaseException { if (this.lager.accounting) { logger.trace(// w w w .j ava2 s. c o m "end(): " + Lager.id(id) + ", ownerDN = '" + ownerDN + "', minutesElapsed = " + minutesElapsed); } Connection c = null; PreparedStatement pstmt = null; PreparedStatement pstmt2 = null; ResultSet rs = null; String uuid; try { c = getConnection(); // begin transaction c.setAutoCommit(false); // check consistency of destroy request // & retrieve necessary items for subsequent sql String creatorDN; Calendar creationTime; long t; int requestedDuration; int CPUCores; int memory; pstmt = c.prepareStatement(SQL_LOAD_DEPLOYMENT); pstmt.setInt(1, id); rs = pstmt.executeQuery(); if (rs == null || !rs.next()) { String err = "active deployment with id " + id + " not found"; logger.error(err); throw new WorkspaceDatabaseException(err); } else { uuid = rs.getString(1); creatorDN = rs.getString(2); t = rs.getLong(3); creationTime = Calendar.getInstance(); creationTime.setTimeInMillis(t); requestedDuration = rs.getInt(4); CPUCores = rs.getInt(5); memory = rs.getInt(6); } if (this.lager.accounting) { logger.trace("end(): found " + Lager.id(id) + ": uuid = " + uuid + ", creation time = " + t + ", requestedDuration = " + requestedDuration + ", CPU cores = " + CPUCores + ", memory = " + memory + ", creator DN = " + creatorDN); } rs.close(); rs = null; if (ownerDN.equals(creatorDN)) { if (this.lager.accounting) { logger.trace(Lager.id(id) + ": creatorDN in DB matches " + "destroy request"); } } else { String err = "active deployment with id " + id + " had " + "non-matching creatorDN. Expected '" + ownerDN + "'," + " stored was '" + creatorDN + "'"; logger.error(err); throw new WorkspaceDatabaseException(err); } // log elapsed time pstmt2 = c.prepareStatement(SQL_UPDATE_END_DEPLOYMENT); pstmt2.setObject(1, new Long(minutesElapsed)); pstmt2.setString(2, uuid); int updated = pstmt2.executeUpdate(); c.commit(); if (this.lager.accounting) { logger.trace(Lager.id(id) + ": updated " + updated + " rows"); } } catch (SQLException e) { logger.error("", e); throw new WorkspaceDatabaseException(e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (pstmt2 != null) { pstmt2.close(); } if (c != null) { c.setAutoCommit(true); returnConnection(c); } } catch (SQLException sql) { logger.error("SQLException in finally cleanup", sql); } } return uuid; }
From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java
/** * Execute given query via a PreparedStatement. * A list of args can be passed to the query. * * Example: runQuery("SELECT * FROM example WHERE test = ?", "test"); * * @param query Query that should be executed * @param args Long, String, or Object arguments *///from w ww.j av a 2 s .c om protected void runQuery(String query, Connection conn, Object... args) { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(query); for (int i = 0; i < args.length; ++i) { if (args[i] instanceof String) { stmt.setString(i + 1, (String) args[i]); } else if (args[i] instanceof Long) { stmt.setLong(i + 1, (Long) args[i]); } else { stmt.setObject(i + 1, args[i]); } } if (stmt.execute()) { ResultSet rset = stmt.getResultSet(); int count = 0; while (rset.next()) { count++; } LOG.info("QUERY(" + query + ") produced unused resultset with " + count + " rows"); } else { int updateCount = stmt.getUpdateCount(); LOG.info("QUERY(" + query + ") Update count: " + updateCount); } } catch (SQLException ex) { throw new SqoopException(CommonRepositoryError.COMMON_0000, query, ex); } finally { closeStatements(stmt); } }
From source file:org.nuxeo.ecm.core.storage.sql.Mapper.java
/** * Updates a row in the database with given explicit values. *//* w w w . j av a 2 s. c o m*/ public void updateSingleRowWithValues(String tableName, Serializable id, Map<String, Serializable> map) throws StorageException { Update update = sqlInfo.getUpdateByIdForKeys(tableName, map.keySet()); Table table = update.getTable(); String sql = update.getStatement(); try { PreparedStatement ps = connection.prepareStatement(sql); try { if (isLogEnabled()) { List<Serializable> values = new LinkedList<Serializable>(); values.addAll(map.values()); values.add(id); logSQL(sql, values); } int i = 1; for (Entry<String, Serializable> entry : map.entrySet()) { String key = entry.getKey(); Serializable value = entry.getValue(); table.getColumn(key).setToPreparedStatement(ps, i++, value); } ps.setObject(i, id); int count = ps.executeUpdate(); logCount(count); } finally { closePreparedStatement(ps); } } catch (SQLException e) { checkConnectionReset(e); throw new StorageException("Could not update: " + sql, e); } }