Java Code Examples for java.sql.PreparedStatement.addBatch()

The following are Jave code examples for showing how to use addBatch() of the java.sql.PreparedStatement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Reer   File: CrossVersionResultsStore.java   View Source Code Vote up 7 votes
private void addOperations(PreparedStatement statement, long testId, String version, MeasuredOperationList operations) throws SQLException {
    for (MeasuredOperation operation : operations) {
        statement.setLong(1, testId);
        statement.setString(2, version);
        statement.setBigDecimal(3, operation.getTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(4, operation.getConfigurationTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(5, operation.getExecutionTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(6, operation.getTotalMemoryUsed().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(7, operation.getTotalHeapUsage().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(8, operation.getMaxHeapUsage().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(9, operation.getMaxUncollectedHeap().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(10, operation.getMaxCommittedHeap().toUnits(DataAmount.BYTES).getValue());
        if (operation.getCompileTotalTime() != null) {
            statement.setBigDecimal(11, operation.getCompileTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        } else {
            statement.setNull(11, Types.DECIMAL);
        }
        if (operation.getGcTotalTime() != null) {
            statement.setBigDecimal(12, operation.getGcTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        } else {
            statement.setNull(12, Types.DECIMAL);
        }
        statement.addBatch();
    }
}
 
Example 2
Project: adept   File: JdbcHelper.java   View Source Code Vote up 6 votes
/**
 * 在'PreparedStatement'中设置SQL语句参数.
 * @param pstmt PreparedStatement实例
 * @param paramsArr 不定长数组参数
 * @return PreparedStatement实例
 * @throws SQLException SQL异常
 */
private static PreparedStatement setBatchPreparedStatementParams(PreparedStatement pstmt,
        Object[]... paramsArr) throws SQLException {
    if (paramsArr == null) {
        return pstmt;
    }

    // 遍历批量执行每条语句的数组参数.
    for (Object[] params: paramsArr) {
        if (params == null) {
            continue;
        }
        setParams(pstmt, params);
        pstmt.addBatch();
    }

    return pstmt;
}
 
Example 3
Project: AeroStory   File: ReportHandler.java   View Source Code Vote up 6 votes
public void addReport(int reporterid, int victimid, int reason, String description, String chatlog) {
  Connection con = DatabaseConnection.getConnection();
        try {
            PreparedStatement ps = con.prepareStatement("INSERT INTO reports (`reporterid`, `victimid`, `reason`, `description`, `chatlog`) VALUES (?, ?, ?, ?, ?)");
            ps.setInt(1, reporterid);
            ps.setInt(2, victimid);
            ps.setInt(3, reason);
            ps.setString(4, description);
            ps.setString(5, chatlog);
            ps.addBatch();
            ps.executeBatch();
            ps.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
}
 
Example 4
Project: alvisnlp   File: ADBBinder.java   View Source Code Vote up 6 votes
public void addAnnReferencesToNakedSecondaryAnnotation(int dbAnnId, Tuple secAnnReferencesHolder, Map<String, Integer> dbAnIdByAlvisAnnId) throws ProcessingException {
    PreparedStatement addAnnRefStatement = getPreparedStatement(PreparedStatementId.AddAnnotationReference);
    try {
        int ordNum = 0;
        for (String role : secAnnReferencesHolder.getRoles()) {
            String referencedAnnAlvisId = secAnnReferencesHolder.getArgument(role).getStringId();
            int referencedAnnId = dbAnIdByAlvisAnnId.get(referencedAnnAlvisId);
            addAnnRefStatement.setInt(1, dbAnnId);
            addAnnRefStatement.setInt(2, referencedAnnId);
            addAnnRefStatement.setString(3, role);
            addAnnRefStatement.setInt(4, ordNum++);
            addAnnRefStatement.addBatch();
        }
        addAnnRefStatement.executeBatch();
    } catch (SQLException ex) {
        logger.log(Level.SEVERE, ex.getMessage());
        throw new ProcessingException("Could not add Annotation references", ex);
    }
}
 
Example 5
Project: dble   File: TravelRecordInsertJob.java   View Source Code Vote up 6 votes
private long insert(Connection con, List<Map<String, String>> list)
        throws SQLException {
    PreparedStatement ps;

    String sql = "insert into travelrecord (id,user_id,traveldate,fee,days) values(?,?,?,?,?)";
    ps = con.prepareStatement(sql);
    for (Map<String, String> map : list) {
        ps.setLong(1, Long.parseLong(map.get("id")));
        ps.setString(2, (String) map.get("user_id"));
        ps.setString(3, (String) map.get("traveldate"));
        ps.setString(4, (String) map.get("fee"));
        ps.setString(5, (String) map.get("days"));
        ps.addBatch();
    }
    ps.executeBatch();
    con.commit();
    ps.clearBatch();
    ps.close();
    return list.size();
}
 
Example 6
Project: OpenVertretung   File: StatementRegressionTest.java   View Source Code Vote up 6 votes
/**
 * Bug #39426 - executeBatch passes most recent PreparedStatement params to
 * StatementInterceptor
 */
public void testBug39426() throws Exception {
    Connection c = null;
    try {
        createTable("testBug39426", "(x int)");
        c = getConnectionWithProps("statementInterceptors=testsuite.regression.StatementRegressionTest$Bug39426Interceptor,useServerPrepStmts=false");
        PreparedStatement ps = c.prepareStatement("insert into testBug39426 values (?)");
        ps.setInt(1, 1);
        ps.addBatch();
        ps.setInt(1, 2);
        ps.addBatch();
        ps.setInt(1, 3);
        ps.addBatch();
        ps.executeBatch();
        List<Integer> vals = Bug39426Interceptor.vals;
        assertEquals(new Integer(1), vals.get(0));
        assertEquals(new Integer(2), vals.get(1));
        assertEquals(new Integer(3), vals.get(2));
    } finally {
        if (c != null) {
            c.close();
        }
    }
}
 
Example 7
Project: big_data   File: ActiveUserBrowserCollector.java   View Source Code Vote up 6 votes
@Override
public void collect(Configuration conf, BaseDimension key, BaseStatsValueWritable value, PreparedStatement pstmt,
		IDimensionConverter converter) throws SQLException, IOException {
	// 进行强制后获取对应的值
	StatsUserDimension statsUser = (StatsUserDimension) key;
	IntWritable activeUserValue = (IntWritable) ((MapWritableValue) value).getValue().get(new IntWritable(-1));

	// 进行参数设置
	int i = 0;
	pstmt.setInt(++i, converter.getDimensionIdByValue(statsUser.getStatsCommon().getPlatform()));
	pstmt.setInt(++i, converter.getDimensionIdByValue(statsUser.getStatsCommon().getDate()));
	pstmt.setInt(++i, converter.getDimensionIdByValue(statsUser.getBrowser()));
	pstmt.setInt(++i, activeUserValue.get());
	pstmt.setString(++i, conf.get(GlobalConstants.RUNNING_DATE_PARAMES));
	pstmt.setInt(++i, activeUserValue.get());

	// 添加到batch中
	pstmt.addBatch();
}
 
Example 8
Project: mycat-src-1.6.1-RELEASE   File: TravelRecordInsertJob.java   View Source Code Vote up 6 votes
private long insert(Connection con, List<Map<String, String>> list)
		throws SQLException {
	PreparedStatement ps;

	String sql = "insert into travelrecord (id,user_id,traveldate,fee,days) values(?,?,?,?,?)";
	ps = con.prepareStatement(sql);
	for (Map<String, String> map : list) {
		ps.setLong(1, Long.parseLong(map.get("id")));
		ps.setString(2, (String) map.get("user_id"));
		ps.setString(3, (String) map.get("traveldate"));
		ps.setString(4, (String) map.get("fee"));
		ps.setString(5, (String) map.get("days"));
		ps.addBatch();
	}
	ps.executeBatch();
	con.commit();
	ps.clearBatch();
	ps.close();
	return list.size();
}
 
Example 9
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
public void lowerRequestedFlag(Connection txn, ContactId c,
		Collection<MessageId> requested) throws DbException {
	PreparedStatement ps = null;
	try {
		String sql = "UPDATE statuses SET requested = FALSE"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		ps.setInt(2, c.getInt());
		for (MessageId m : requested) {
			ps.setBytes(1, m.getBytes());
			ps.addBatch();
		}
		int[] batchAffected = ps.executeBatch();
		if (batchAffected.length != requested.size())
			throw new DbStateException();
		for (int rows: batchAffected) {
			if (rows < 0) throw new DbStateException();
			if (rows > 1) throw new DbStateException();
		}
		ps.close();
	} catch (SQLException e) {
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 10
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
public void lowerAckFlag(Connection txn, ContactId c,
		Collection<MessageId> acked) throws DbException {
	PreparedStatement ps = null;
	try {
		String sql = "UPDATE statuses SET ack = FALSE"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		ps.setInt(2, c.getInt());
		for (MessageId m : acked) {
			ps.setBytes(1, m.getBytes());
			ps.addBatch();
		}
		int[] batchAffected = ps.executeBatch();
		if (batchAffected.length != acked.size())
			throw new DbStateException();
		for (int rows : batchAffected) {
			if (rows < 0) throw new DbStateException();
			if (rows > 1) throw new DbStateException();
		}
		ps.close();
	} catch (SQLException e) {
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 11
Project: aliyun-maxcompute-data-collectors   File: UpdateOutputFormat.java   View Source Code Vote up 6 votes
@Override
/** {@inheritDoc} */
protected PreparedStatement getPreparedStatement(
    List<SqoopRecord> userRecords) throws SQLException {

  PreparedStatement stmt = null;

  // Synchronize on connection to ensure this does not conflict
  // with the operations in the update thread.
  Connection conn = getConnection();
  synchronized (conn) {
    stmt = conn.prepareStatement(getUpdateStatement());
  }

  // Inject the record parameters into the UPDATE and WHERE clauses.  This
  // assumes that the update key column is the last column serialized in
  // by the underlying record. Our code auto-gen process for exports was
  // responsible for taking care of this constraint.
  for (SqoopRecord record : userRecords) {
    record.write(stmt, 0);
    stmt.addBatch();
  }

  return stmt;
}
 
Example 12
Project: Reer   File: BaseCrossBuildResultsStore.java   View Source Code Vote up 5 votes
private void addOperations(PreparedStatement statement, long executionId, BuildDisplayInfo displayInfo, MeasuredOperationList operations) throws SQLException {
    for (MeasuredOperation operation : operations) {
        statement.setLong(1, executionId);
        statement.setString(2, displayInfo.getProjectName());
        statement.setString(3, displayInfo.getDisplayName());
        statement.setObject(4, toArray(displayInfo.getTasksToRun()));
        statement.setObject(5, toArray(displayInfo.getArgs()));
        statement.setObject(6, toArray(displayInfo.getGradleOpts()));
        statement.setObject(7, displayInfo.getDaemon());
        statement.setBigDecimal(8, operation.getTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(9, operation.getConfigurationTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(10, operation.getExecutionTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(11, operation.getTotalMemoryUsed().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(12, operation.getTotalHeapUsage().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(13, operation.getMaxHeapUsage().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(14, operation.getMaxUncollectedHeap().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(15, operation.getMaxCommittedHeap().toUnits(DataAmount.BYTES).getValue());
        if (operation.getCompileTotalTime() != null) {
            statement.setBigDecimal(16, operation.getCompileTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        } else {
            statement.setNull(16, Types.DECIMAL);
        }
        if (operation.getGcTotalTime() != null) {
            statement.setBigDecimal(17, operation.getGcTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        } else {
            statement.setNull(17, Types.DECIMAL);
        }
        statement.addBatch();
    }
}
 
Example 13
Project: BibliotecaPS   File: StatementRegressionTest.java   View Source Code Vote up 5 votes
/**
 * Tests fix for BUG#20029 - NPE thrown from executeBatch().
 * 
 * @throws Exception
 */
public void testBug20029() throws Exception {
    createTable("testBug20029", ("(field1 int)"));

    long initialTimeout = 20; // may need to raise this depending on environment we try and do this automatically in this testcase

    for (int i = 0; i < 10; i++) {
        final Connection toBeKilledConn = getConnectionWithProps(new Properties());
        final long timeout = initialTimeout;
        PreparedStatement toBeKilledPstmt = null;

        try {
            toBeKilledPstmt = ((com.mysql.jdbc.Connection) toBeKilledConn).clientPrepareStatement("INSERT INTO testBug20029 VALUES (?)");

            for (int j = 0; j < 1000; j++) {
                toBeKilledPstmt.setInt(1, j);
                toBeKilledPstmt.addBatch();
            }

            Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        sleep(timeout);
                        toBeKilledConn.close();
                    } catch (Throwable thr) {

                    }
                }
            };

            t.start();

            try {
                if (!toBeKilledConn.isClosed()) {
                    initialTimeout *= 2;
                    continue;
                }

                toBeKilledPstmt.executeBatch();
                fail("Should've caught a SQLException for the statement being closed here");
            } catch (BatchUpdateException batchEx) {
                assertEquals("08003", batchEx.getSQLState());
                break;
            } catch (SQLException sqlEx) {
                assertEquals("08003", sqlEx.getSQLState());
                break;
            }

            fail("Connection didn't close while in the middle of PreparedStatement.executeBatch()");
        } finally {
            if (toBeKilledPstmt != null) {
                toBeKilledPstmt.close();
            }

            if (toBeKilledConn != null) {
                toBeKilledConn.close();
            }
        }
    }
}
 
Example 14
Project: parabuild-ci   File: TestBatchBug.java   View Source Code Vote up 5 votes
static void populateTable(Connection con) throws SQLException {

        long      startTime = System.currentTimeMillis();
        Timestamp now       = new Timestamp(startTime);

        con.setAutoCommit(false);

        String            sql  = createInsertSQL(true, false);
        PreparedStatement prep = con.prepareStatement(sql);

        prep.clearParameters();
        prep.setString(1, "xxx");
        prep.setTimestamp(2, now);    // last_update

        for (int ii = 0; ii < DECIMAL_FIELDS_PER_DATASET; ii++) {
            prep.setDouble(ii + 3, 0.123456789);    // Wert
        }

        prep.addBatch();
        prep.setString(1, "yyy");
        prep.setTimestamp(2, now);    // last_update

        for (int ii = 0; ii < DECIMAL_FIELDS_PER_DATASET; ii++) {
            prep.setDouble(ii + 3, 0.123456789);    // Wert
        }

        prep.addBatch();

        int[] updateCounts = prep.executeBatch();

        con.setAutoCommit(true);
        prep.close();
    }
 
Example 15
Project: aliyun-maxcompute-data-collectors   File: MySQLUpsertOutputFormat.java   View Source Code Vote up 5 votes
/**
  * {@inheritDoc}
  */
 @Override
 protected PreparedStatement getPreparedStatement(
     List<SqoopRecord> userRecords) throws SQLException {

   PreparedStatement stmt = null;

   // Synchronize on connection to ensure this does not conflict
   // with the operations in the update thread.
   Connection conn = getConnection();
   synchronized (conn) {
stmt = conn.prepareStatement(getUpdateStatement(userRecords.size()));
   }

   // Inject the record parameters into the UPDATE and WHERE clauses.  This
   // assumes that the update key column is the last column serialized in
   // by the underlying record. Our code auto-gen process for exports was
   // responsible for taking care of this constraint.
   int i = 0;
   for (SqoopRecord record : userRecords) {
     record.write(stmt, i);
     i += columnNames.length;
   }
   stmt.addBatch();

   return stmt;
 }
 
Example 16
Project: improving-your-relational-database-architecture   File: SeedProductsWithBatchApplication.java   View Source Code Vote up 5 votes
private void insertOptionValues(PreparedStatement insert_option_values_stmt, long option_id, String... values) throws SQLException {
	for (String value : values) {
		insert_option_values_stmt.setLong(1, option_id);
		insert_option_values_stmt.setString(2, value);
		insert_option_values_stmt.addBatch();
	}
}
 
Example 17
Project: cf-mta-deploy-service   File: AlterOperationTableTimestampStoringColumns.java   View Source Code Vote up 5 votes
@Override
public void setUpdateStatementParameters(PreparedStatement preparedStatement, List<TransformedOperation> transformedData)
    throws SQLException {
    for (TransformedOperation operation : transformedData) {
        preparedStatement.setTimestamp(1, operation.startedAt);
        preparedStatement.setTimestamp(2, operation.endedAt);
        preparedStatement.setString(3, operation.processId);
        preparedStatement.addBatch();
        logger.debug(String.format("Updated operation with ID '%s' with start time: '%s' and end time '%s'.", operation.processId,
            operation.startedAt, operation.endedAt));
    }
}
 
Example 18
Project: neoscada   File: BaseStorageDao.java   View Source Code Vote up 5 votes
private void performUpdateCommand ( final UUID id, final String comment, final Connection con ) throws SQLException
{
    final PreparedStatement stm1 = con.prepareStatement ( String.format ( getDeleteAttributesSql (), getSchema () ) );
    try
    {
        stm1.setString ( 1, id.toString () );
        stm1.setString ( 2, Event.Fields.COMMENT.getName () );
        stm1.addBatch ();
        stm1.execute ();

        final PreparedStatement stm2 = con.prepareStatement ( String.format ( getInsertAttributesSql (), getSchema () ) );
        try
        {
            stm2.setString ( 1, id.toString () );
            stm2.setString ( 2, Event.Fields.COMMENT.getName () );
            stm2.setString ( 3, VariantType.STRING.name () );
            stm2.setString ( 4, clip ( getMaxLength (), comment ) );
            stm2.setNull ( 5, Types.INTEGER );
            stm2.setNull ( 6, Types.DOUBLE );
            stm2.addBatch ();
            stm2.execute ();

            con.commit ();
        }
        finally
        {
            closeStatement ( stm2 );
        }
    }
    finally
    {
        closeStatement ( stm1 );
    }
}
 
Example 19
Project: spanner-jdbc-converter   File: UploadWorker.java   View Source Code Vote up 4 votes
@Override
public void run() throws SQLException
{
	try (Connection destination = DriverManager.getConnection(config.getUrlDestination());
			Connection source = DriverManager.getConnection(config.getUrlSource()))
	{
		ConverterUtils converterUtils = new ConverterUtils(config);
		log.fine(sourceTable + ": Starting copying " + totalRecordCount + " records");

		destination.setAutoCommit(false);
		String sql = "INSERT INTO " + destinationTable + " (" + insertCols.getColumnNames() + ") VALUES \n";
		sql = sql + "(" + insertCols.getColumnParameters() + ")";
		PreparedStatement statement = destination.prepareStatement(sql);

		long lastRecord = beginOffset + totalRecordCount;
		long recordCount = 0;
		long currentOffset = beginOffset;
		while (true)
		{
			long limit = Math.min(batchSize, lastRecord - currentOffset);
			String select = selectFormat.replace("$COLUMNS", selectCols.getColumnNames());
			select = select.replace("$TABLE", sourceTable);
			select = select.replace("$PRIMARY_KEY", selectCols.getPrimaryKeyColumns());
			select = select.replace("$BATCH_SIZE", String.valueOf(limit));
			select = select.replace("$OFFSET", String.valueOf(currentOffset));
			try (ResultSet rs = source.createStatement().executeQuery(select))
			{
				while (rs.next())
				{
					int index = 1;
					for (Integer type : insertCols.getColumnTypes())
					{
						Object object = rs.getObject(index);
						statement.setObject(index, object, type);
						byteCount += converterUtils.getActualDataSize(type, object);
						index++;
					}
					if (config.isUseJdbcBatching())
						statement.addBatch();
					else
						statement.executeUpdate();
					recordCount++;
				}
				if (config.isUseJdbcBatching())
					statement.executeBatch();
			}
			destination.commit();
			log.fine(sourceTable + ": Records copied so far: " + recordCount + " of " + totalRecordCount);
			currentOffset = currentOffset + batchSize;
			if (recordCount >= totalRecordCount)
				break;
		}
	}
	log.fine(sourceTable + ": Finished copying");
}
 
Example 20
Project: lams   File: SqlLoadMigrationTask.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
public void migrate(MigrationContext ctx) throws MigrationException
{
    DataSourceMigrationContext context = (DataSourceMigrationContext) ctx;

    Connection conn = null;
    PreparedStatement stmt = null;
    try
    {
        conn = context.getConnection();
        stmt = conn.prepareStatement(getStatmentSql());
        List rows = getData(getResourceAsStream());
        int rowCount = rows.size();
        for (int i = 0; i < rowCount; i++)
        {
            String data = (String) rows.get(i);
            boolean loadRowFlag = insert(data, stmt);
            if (loadRowFlag)
            {
                stmt.addBatch();
                if (i % 50 == 0)
                {
                    stmt.executeBatch();
                }
            }
        }
        stmt.executeBatch();
        context.commit();
    }
    catch (Exception e)
    {
        String message = getName() + ": Error running SQL \"" + getStatmentSql() + "\"";
        log.error(message, e);
        if (e instanceof SQLException)
        {
            if (((SQLException) e).getNextException() != null)
            {
                log.error("Chained SQL Exception", ((SQLException) e).getNextException());
            }
        }

        context.rollback();

        throw new MigrationException(message, e);
    }
    finally
    {
        SqlUtil.close(conn, stmt, null);
    }
}