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.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java
private void massUpdateTaskGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) { if (CollectionUtils.isNotEmpty(taskGanttItems)) { Lock lock = DistributionLockUtil.getLock("gantt-task-service" + sAccountId); try {/*from w w w . j a va 2 s. com*/ final long now = new GregorianCalendar().getTimeInMillis(); if (lock.tryLock(30, TimeUnit.SECONDS)) { try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(false); PreparedStatement batchTasksStatement = connection.prepareStatement( "UPDATE `m_prj_task` SET " + "taskname = ?, `startdate` = ?, `enddate` = ?, " + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignUser`=?, `ganttindex`=?, " + "`milestoneId`=?, `parentTaskId`=? WHERE `id` = ?"); for (int i = 0; i < taskGanttItems.size(); i++) { TaskGanttItem ganttItem = taskGanttItems.get(i); if (ProjectTypeConstants.TASK.equals(ganttItem.getType())) { batchTasksStatement.setString(1, ganttItem.getName()); batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate())); batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate())); batchTasksStatement.setDate(4, new Date(now)); batchTasksStatement.setDouble(5, ganttItem.getProgress()); batchTasksStatement.setString(6, ganttItem.getAssignUser()); batchTasksStatement.setInt(7, ganttItem.getGanttIndex()); batchTasksStatement.setObject(8, ganttItem.getMilestoneId()); batchTasksStatement.setObject(9, ganttItem.getParentTaskId()); batchTasksStatement.setInt(10, ganttItem.getId()); batchTasksStatement.addBatch(); } } batchTasksStatement.executeBatch(); connection.commit(); } } } catch (Exception e) { throw new MyCollabException(e); } finally { DistributionLockUtil.removeLock("gantt-task-service" + sAccountId); lock.unlock(); } } }
From source file:at.bestsolution.persistence.java.Util.java
public static void setValue(PreparedStatement pstmt, int parameterIndex, TypedValue value) throws SQLException { if (value.value == null) { int sqlType; switch (value.type) { case INT: sqlType = Types.INTEGER; break; case DOUBLE: sqlType = Types.DECIMAL; break; case FLOAT: sqlType = Types.FLOAT; break; case BOOLEAN: sqlType = Types.BOOLEAN; break; case LONG: sqlType = Types.BIGINT; break; case STRING: sqlType = Types.VARCHAR; break; case BLOB: sqlType = Types.BLOB; break; case CLOB: sqlType = Types.CLOB; break; case TIMESTAMP: sqlType = Types.TIMESTAMP; break; default:/* w w w.java2s . c o m*/ sqlType = Types.OTHER; break; } pstmt.setNull(parameterIndex, sqlType); } else { switch (value.type) { case INT: pstmt.setInt(parameterIndex, ((Number) value.value).intValue()); break; case DOUBLE: pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue()); break; case FLOAT: pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue()); break; case BOOLEAN: pstmt.setBoolean(parameterIndex, Boolean.TRUE.equals(value.value)); break; case LONG: pstmt.setLong(parameterIndex, ((Number) value.value).longValue()); break; case STRING: pstmt.setString(parameterIndex, (String) value.value); break; case TIMESTAMP: if (value.value instanceof Timestamp) { pstmt.setTimestamp(parameterIndex, (Timestamp) value.value); } else { pstmt.setTimestamp(parameterIndex, new Timestamp(((Date) value.value).getTime())); } break; case UNKNOWN: pstmt.setObject(parameterIndex, value.value); break; default: throw new IllegalStateException("Unknown type"); } } }
From source file:edu.ku.brc.specify.toycode.RegPivot.java
/** * @param hash/*from ww w . ja va2 s .c o m*/ * @param recordType * @param pStmt * @param dbFieldTypes * @param dbFieldNames * @param inxToName * @throws SQLException */ private void writeHash(final HashMap<String, HashMap<String, Object>> hash, final Integer recordType, final PreparedStatement pStmt, final Vector<Integer> dbFieldTypes, final Vector<String> dbFieldNames, final HashMap<Integer, String> inxToName) throws SQLException { int totalCnt = hash.size(); int cnt = 0; for (String idKey : hash.keySet()) { cnt++; if (cnt % 500 == 0) System.out.println(cnt + " / " + totalCnt); HashMap<String, Object> nameToVals = hash.get(idKey); if (recordType != null) { pStmt.setInt(dbFieldNames.size() + 1, (Integer) recordType); } for (int i = 0; i < dbFieldNames.size(); i++) { int fInx = i + 1; String name = inxToName.get(i); Object value = nameToVals.get(name); pStmt.setObject(fInx, null); int typ = dbFieldTypes.get(i); if (value != null) { if (value instanceof Integer) { pStmt.setInt(fInx, (Integer) value); } else if (value instanceof String) { pStmt.setString(fInx, (String) value); } else if (value instanceof Timestamp) { pStmt.setTimestamp(fInx, (Timestamp) value); } else { System.err.println("Unhandled class: " + value.getClass().getName()); } } else { pStmt.setObject(fInx, null); } } pStmt.executeUpdate(); } }
From source file:User_Manager.User_TblJDBCTemplate.java
public boolean follow_Unfollow(int loggedin_user, int profile_user, int cmd) throws SQLException { /* /*from www . j a v a 2 s . c o m*/ follower- is the logged in user sending request to follow/unfollow followed- is the user who follower wants to follow or unfollow */ try { con = conn.getDataSource().getConnection(); PreparedStatement st = con.prepareStatement( "SELECT A.following,B.followers FROM login_tbl A, login_tbl B where A.uid=? and B.uid=?;"); st.setInt(1, loggedin_user); st.setInt(2, profile_user); ResultSet rs = st.executeQuery(); rs.next(); ArrayList<Integer> profile_user_followers = gson.fromJson(rs.getString("followers"), ArrayList.class); ArrayList<Integer> loggedin_user_following = gson.fromJson(rs.getString("following"), ArrayList.class); switch (cmd) { case 0: {//unfollow profile_user_followers.remove(loggedin_user + .0); loggedin_user_following.remove(profile_user + .0); // } break; case 1: {//follow profile_user_followers.add(loggedin_user); loggedin_user_following.add(profile_user); } break; } // IMPORTANT Make a transaction or a batch execution here st = con.prepareStatement("UPDATE login_tbl SET following=? WHERE uid=?;"); st.setObject(1, loggedin_user_following.toString()); st.setObject(2, loggedin_user); //System.out.println("query for following"+st); st.execute(); //st.addBatch(); st = con.prepareStatement("UPDATE login_tbl SET followers=? WHERE uid=?;"); st.setObject(1, profile_user_followers.toString()); st.setObject(2, profile_user); //System.out.println("query for followers"+st); st.execute(); //st.addBatch(); //int rslt[]=st.executeBatch(); return true; } catch (Exception e) { return false; } finally { con.close(); } }
From source file:edu.jhuapl.openessence.datasource.jdbc.JdbcOeDataSource.java
protected void setArguments(List<Object> arguments, PreparedStatement pStmt) throws SQLException { int argCount = 1; for (Object o : arguments) { // TODO NEED TO ADDRESS THE USE CASES FOR THIS null...POKUAM1...what if not nullable column? if (o == null) { pStmt.setObject(argCount, null); } else if (o instanceof java.sql.Timestamp) { pStmt.setTimestamp(argCount, (java.sql.Timestamp) o); } else if (o instanceof java.util.Date) { pStmt.setTimestamp(argCount, new java.sql.Timestamp(((java.util.Date) o).getTime())); } else if (o instanceof Integer) { pStmt.setInt(argCount, (Integer) o); } else if (o instanceof Long) { pStmt.setLong(argCount, (Long) o); } else if (o instanceof Float) { pStmt.setFloat(argCount, (Float) o); } else if (o instanceof Double) { pStmt.setDouble(argCount, (Double) o); } else if (o instanceof String) { pStmt.setString(argCount, (String) o); } else if (o instanceof Boolean) { pStmt.setBoolean(argCount, (Boolean) o); } else {//ww w. ja v a 2 s . c o m throw new AssertionError("Unexpected object " + o + " " + o.getClass()); } argCount += 1; } }
From source file:org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule.java
RowKey execInsert(DbExternalVariable dbev, Locator locator, RowKey keys, RowVal values) throws SQLException { Connection conn = dbev.dataSource.getConnection(); PreparedStatement stmt = null; try {/*from w ww. j a va2 s. c o m*/ if (__log.isDebugEnabled()) { __log.debug("execInsert: keys=" + keys + " values=" + values); __log.debug("Prepare statement: " + dbev.insert); __log.debug("missingDatabaseGeneratedValues: " + keys.missingDatabaseGeneratedValues()); __log.debug("_autoColNames: " + ObjectPrinter.stringifyNvList(dbev._autoColNames)); } stmt = keys.missingDatabaseGeneratedValues() ? conn.prepareStatement(dbev.insert, dbev._autoColNames) : conn.prepareStatement(dbev.insert); int idx = 1; for (Column c : dbev._inscolumns) { Object val = c.getValue(c.name, keys, values, locator.iid); values.put(c.name, val); if (__log.isDebugEnabled()) __log.debug("Set parameter " + idx + ": " + val); if (val == null) stmt.setNull(idx, c.dataType); else stmt.setObject(idx, val); idx++; } stmt.execute(); for (Column ck : keys._columns) { Object val = values.get(ck.name); if (__log.isDebugEnabled()) __log.debug("Key " + ck.name + ": " + val); keys.put(ck.name, val); } if (keys.missingDatabaseGeneratedValues()) { // With JDBC 3, we can get the values of the key columns (if the db supports it) ResultSet keyRS = stmt.getGeneratedKeys(); try { if (keyRS == null) throw new SQLException("Database did not return generated keys"); keyRS.next(); for (Column ck : keys._columns) { Object value = keyRS.getObject(ck.idx + 1); if (__log.isDebugEnabled()) __log.debug("Generated key " + ck.name + ": " + value); keys.put(ck.name, value); } } finally { keyRS.close(); } } return keys; } finally { if (stmt != null) stmt.close(); try { conn.close(); } catch (SQLException e) { // ignore } } }
From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java
private void massUpdateBugGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) { if (CollectionUtils.isNotEmpty(taskGanttItems)) { Lock lock = DistributionLockUtil.getLock("gantt-bug-service" + sAccountId); try {/*from ww w .j a v a2s . c o m*/ final long now = new GregorianCalendar().getTimeInMillis(); if (lock.tryLock(30, TimeUnit.SECONDS)) { try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(false); PreparedStatement batchTasksStatement = connection.prepareStatement( "UPDATE `m_tracker_bug` SET " + "summary = ?, `startdate` = ?, `enddate` = ?, " + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignuser`=?, `ganttindex`=?, " + "`milestoneId`=? WHERE `id` = ?"); for (int i = 0; i < taskGanttItems.size(); i++) { TaskGanttItem ganttItem = taskGanttItems.get(i); if (ProjectTypeConstants.BUG.equals(ganttItem.getType())) { batchTasksStatement.setString(1, ganttItem.getName()); batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate())); batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate())); batchTasksStatement.setDate(4, new Date(now)); batchTasksStatement.setDouble(5, MoreObjects.firstNonNull(ganttItem.getProgress(), 0d)); batchTasksStatement.setString(6, ganttItem.getAssignUser()); batchTasksStatement.setInt(7, ganttItem.getGanttIndex()); batchTasksStatement.setObject(8, ganttItem.getMilestoneId()); batchTasksStatement.setInt(9, ganttItem.getId()); batchTasksStatement.addBatch(); } } batchTasksStatement.executeBatch(); connection.commit(); } } } catch (Exception e) { throw new MyCollabException(e); } finally { DistributionLockUtil.removeLock("gantt-bug-service" + sAccountId); lock.unlock(); } } }
From source file:org.eclipse.ecr.core.storage.sql.jdbc.JDBCMapper.java
@Override public PartialList<Serializable> query(String query, QueryFilter queryFilter, boolean countTotal) throws StorageException { QueryMaker queryMaker = findQueryMaker(query); if (queryMaker == null) { throw new StorageException("No QueryMaker accepts query: " + query); }//from ww w . j a v a2s .c o m QueryMaker.Query q = queryMaker.buildQuery(sqlInfo, model, pathResolver, query, queryFilter); if (q == null) { logger.log("Query cannot return anything due to conflicting clauses"); return new PartialList<Serializable>(Collections.<Serializable>emptyList(), 0); } long limit = queryFilter.getLimit(); long offset = queryFilter.getOffset(); if (logger.isLogEnabled()) { String sql = q.selectInfo.sql; if (limit != 0) { sql += " -- LIMIT " + limit + " OFFSET " + offset; } if (countTotal) { sql += " -- COUNT TOTAL"; } logger.logSQL(sql, q.selectParams); } String sql = q.selectInfo.sql; if (!countTotal && limit > 0 && sqlInfo.dialect.supportsPaging()) { // full result set not needed for counting sql += " " + sqlInfo.dialect.getPagingClause(limit, offset); limit = 0; offset = 0; } PreparedStatement ps = null; try { ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); int i = 1; for (Object object : q.selectParams) { if (object instanceof Calendar) { Calendar cal = (Calendar) object; Timestamp ts = new Timestamp(cal.getTimeInMillis()); ps.setTimestamp(i++, ts, cal); // cal passed for timezone } else if (object instanceof String[]) { Array array = sqlInfo.dialect.createArrayOf(Types.VARCHAR, (Object[]) object, connection); ps.setArray(i++, array); } else { ps.setObject(i++, object); } } ResultSet rs = ps.executeQuery(); // limit/offset long totalSize = -1; boolean available; if ((limit == 0) || (offset == 0)) { available = rs.first(); if (!available) { totalSize = 0; } if (limit == 0) { limit = -1; // infinite } } else { available = rs.absolute((int) offset + 1); } Column column = q.selectInfo.whatColumns.get(0); List<Serializable> ids = new LinkedList<Serializable>(); int rowNum = 0; while (available && (limit != 0)) { Serializable id = column.getFromResultSet(rs, 1); ids.add(id); rowNum = rs.getRow(); available = rs.next(); limit--; } // total size if (countTotal && (totalSize == -1)) { if (!available && (rowNum != 0)) { // last row read was the actual last totalSize = rowNum; } else { // available if limit reached with some left // rowNum == 0 if skipped too far rs.last(); totalSize = rs.getRow(); } } if (logger.isLogEnabled()) { logger.logIds(ids, countTotal, totalSize); } return new PartialList<Serializable>(ids, totalSize); } catch (Exception e) { checkConnectionReset(e); throw new StorageException("Invalid query: " + query, e); } finally { if (ps != null) { try { closeStatement(ps); } catch (SQLException e) { log.error("Cannot close connection", e); } } } }
From source file:com.linkedin.pinot.integration.tests.BaseClusterIntegrationTest.java
public static void createH2SchemaAndInsertAvroFiles(List<File> avroFiles, Connection connection) { try {/*w w w .j a va2 s . c o m*/ connection.prepareCall("DROP TABLE IF EXISTS mytable"); File schemaAvroFile = avroFiles.get(0); DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(); DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(schemaAvroFile, datumReader); Schema schema = dataFileReader.getSchema(); List<Schema.Field> fields = schema.getFields(); List<String> columnNamesAndTypes = new ArrayList<String>(fields.size()); int columnCount = 0; for (Schema.Field field : fields) { String fieldName = field.name(); Schema.Type fieldType = field.schema().getType(); switch (fieldType) { case UNION: List<Schema> types = field.schema().getTypes(); String columnNameAndType; String typeName = types.get(0).getName(); if (typeName.equalsIgnoreCase("int")) { typeName = "bigint"; } if (types.size() == 1) { columnNameAndType = fieldName + " " + typeName + " not null"; } else { columnNameAndType = fieldName + " " + typeName; } columnNamesAndTypes.add(columnNameAndType.replace("string", "varchar(128)")); ++columnCount; break; case ARRAY: String elementTypeName = field.schema().getElementType().getName(); if (elementTypeName.equalsIgnoreCase("int")) { elementTypeName = "bigint"; } elementTypeName = elementTypeName.replace("string", "varchar(128)"); for (int i = 0; i < MAX_ELEMENTS_IN_MULTI_VALUE; i++) { columnNamesAndTypes.add(fieldName + "__MV" + i + " " + elementTypeName); } ++columnCount; break; case BOOLEAN: case INT: case LONG: case FLOAT: case DOUBLE: case STRING: String fieldTypeName = fieldType.getName(); if (fieldTypeName.equalsIgnoreCase("int")) { fieldTypeName = "bigint"; } columnNameAndType = fieldName + " " + fieldTypeName + " not null"; columnNamesAndTypes.add(columnNameAndType.replace("string", "varchar(128)")); ++columnCount; break; case RECORD: // Ignore records continue; default: // Ignore other avro types LOGGER.warn("Ignoring field {} of type {}", fieldName, field.schema()); } } connection.prepareCall("create table mytable(" + StringUtil.join(",", columnNamesAndTypes.toArray(new String[columnNamesAndTypes.size()])) + ")").execute(); long start = System.currentTimeMillis(); StringBuilder params = new StringBuilder("?"); for (int i = 0; i < columnNamesAndTypes.size() - 1; i++) { params.append(",?"); } PreparedStatement statement = connection .prepareStatement("INSERT INTO mytable VALUES (" + params.toString() + ")"); dataFileReader.close(); for (File avroFile : avroFiles) { datumReader = new GenericDatumReader<GenericRecord>(); dataFileReader = new DataFileReader<GenericRecord>(avroFile, datumReader); GenericRecord record = null; while (dataFileReader.hasNext()) { record = dataFileReader.next(record); int jdbcIndex = 1; for (int avroIndex = 0; avroIndex < columnCount; ++avroIndex) { Object value = record.get(avroIndex); if (value instanceof GenericData.Array) { GenericData.Array array = (GenericData.Array) value; for (int i = 0; i < MAX_ELEMENTS_IN_MULTI_VALUE; i++) { if (i < array.size()) { value = array.get(i); if (value instanceof Utf8) { value = value.toString(); } } else { value = null; } statement.setObject(jdbcIndex, value); ++jdbcIndex; } } else { if (value instanceof Utf8) { value = value.toString(); } statement.setObject(jdbcIndex, value); ++jdbcIndex; } } statement.execute(); } dataFileReader.close(); } LOGGER.info("Insertion took " + (System.currentTimeMillis() - start)); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.alfaariss.oa.engine.requestor.jdbc.JDBCFactory.java
/** * @see com.alfaariss.oa.engine.core.requestor.factory.IRequestorPoolFactory#getRequestor(java.lang.Object, java.lang.String) *///from ww w. j a v a 2 s . c om @Override public IRequestor getRequestor(Object id, String type) throws RequestorException { IRequestor oRequestor = null; Connection oConnection = null; PreparedStatement oPreparedStatement = null; ResultSet rsRequestor = null; ResultSet rsProperties = null; try { oConnection = _oDataSource.getConnection(); StringBuffer sbQuery = new StringBuffer("SELECT * FROM "); sbQuery.append(_sRequestorsTable); sbQuery.append(" WHERE "); sbQuery.append(type); sbQuery.append(" =?"); oPreparedStatement = oConnection.prepareStatement(sbQuery.toString()); oPreparedStatement.setObject(1, id); rsRequestor = oPreparedStatement.executeQuery(); if (rsRequestor.next()) { oPreparedStatement = oConnection.prepareStatement(_sQuerySelectRequestorProperties); oPreparedStatement.setString(1, rsRequestor.getString(JDBCRequestor.COLUMN_ID)); rsProperties = oPreparedStatement.executeQuery(); JDBCRequestor oJDBCRequestor = new JDBCRequestor(rsRequestor, rsProperties); oRequestor = oJDBCRequestor.getRequestor(); _logger.debug("Retrieved requestor: " + oRequestor); } else _logger.debug("Requestor not found with alternate ID: " + id); } catch (SQLException e) { StringBuffer sbError = new StringBuffer( "SQL error during database retrieval, when selecting requestor with alternate id '"); sbError.append(id); sbError.append("' of type: "); sbError.append(type); _logger.error(sbError.toString(), e); throw new RequestorException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (Exception e) { StringBuffer sbError = new StringBuffer( "Internal error during database retrieval, when selecting requestor with alternate id '"); sbError.append(id); sbError.append("' of type: "); sbError.append(type); _logger.fatal(sbError.toString(), e); throw new RequestorException(SystemErrors.ERROR_INTERNAL); } finally { try { if (rsRequestor != null) rsRequestor.close(); } catch (Exception e) { _logger.error("Could not close requestor resultset", e); } try { if (rsProperties != null) rsProperties.close(); } catch (Exception e) { _logger.error("Could not close requestor properties resultset", e); } try { if (oPreparedStatement != null) oPreparedStatement.close(); } catch (Exception e) { _logger.error("Could not close statement", e); } try { if (oConnection != null) oConnection.close(); } catch (Exception e) { _logger.error("Could not close connection", e); } } return oRequestor; }