List of usage examples for java.sql Statement addBatch
void addBatch(String sql) throws SQLException;
Statement
object. From source file:it.cnr.icar.eric.server.persistence.rdb.AbstractDAO.java
/** * Does a bulk delete of a Collection of objects that match the type for this persister. * *//*from ww w . j av a 2 s.c o m*/ public void delete(@SuppressWarnings("rawtypes") List objects) throws RegistryException { //Return immediatley if no objects to insert if (objects.size() == 0) { return; } log.trace(ServerResourceBundle.getInstance().getString("message.DeletingRowsInTable", new Object[] { new Integer(objects.size()), getTableName() })); action = DAO_ACTION_DELETE; Statement stmt = null; try { stmt = context.getConnection().createStatement(); @SuppressWarnings("rawtypes") Iterator iter = objects.iterator(); while (iter.hasNext()) { Object obj = iter.next(); prepareToDelete(obj); String str = getSQLStatementFragment(obj); log.trace("stmt = " + str); stmt.addBatch(str); } @SuppressWarnings("unused") int[] updateCounts = stmt.executeBatch(); iter = objects.iterator(); while (iter.hasNext()) { Object obj = iter.next(); onDelete(obj); } } catch (SQLException e) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e); throw new RegistryException(e); } finally { closeStatement(stmt); } }
From source file:org.hyperic.hq.events.server.session.RegisteredTriggerManagerImpl.java
@PostConstruct public void cleanupRegisteredTriggers() { Connection conn = null;/*from www . j a va 2s .c o m*/ Statement stmt = null; Boolean autocommit = null; boolean commit = false; try { conn = dbUtil.getConnection(); autocommit = Boolean.valueOf(conn.getAutoCommit()); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.addBatch("update EAM_ALERT_CONDITION set trigger_id = null " + "WHERE exists (" + "select 1 from EAM_ALERT_DEFINITION WHERE deleted = '1' " + "AND EAM_ALERT_CONDITION.alert_definition_id = id" + ")"); stmt.addBatch("delete from EAM_REGISTERED_TRIGGER WHERE exists (" + "select 1 from EAM_ALERT_DEFINITION WHERE deleted = '1' " + "AND EAM_REGISTERED_TRIGGER.alert_definition_id = id" + ")"); int[] rows = stmt.executeBatch(); conn.commit(); commit = true; log.info("disassociated " + rows[0] + " triggers in EAM_ALERT_CONDITION" + " from their deleted alert definitions"); log.info("deleted " + rows[1] + " rows from EAM_REGISTERED_TRIGGER"); } catch (SQLException e) { log.error(e, e); } finally { resetAutocommit(conn, autocommit); if (!commit) rollback(conn); DBUtil.closeJDBCObjects(RegisteredTriggerManagerImpl.class.getName(), conn, stmt, null); } }
From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java
public DBStore(BaseConnector connector) { Connection connection = null; logger = Logger.getLogger(this.getClass().getPackage().getName()); logger.log(Level.INFO, "Initialize DBStore "); this.connector = connector; //each connector instance has its own table in the same database this.instance_table = "i_" + connector.getInstanceName(); Statement Stmt = null;/* w ww.j av a 2 s .c o m*/ ResultSet RS = null; DatabaseMetaData dbm = null; boolean table_exists = false; try { //check if the datasource/database exists Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); ds = (DataSource) envCtx.lookup(BaseConstants.CONNECTOR_DATASOURCE); connection = ds.getConnection(); connection.setAutoCommit(true); dbm = connection.getMetaData(); logger.log(Level.INFO, "Connected to databaseType " + dbm.getDatabaseProductName()); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing Store Datasource " + ex); connection = null; return; } try { if (dbm.getDatabaseProductName().equals("MySQL")) { //check if the per-connector table exists logger.log(Level.FINE, "Checking to see if connector DB exists..."); Stmt = connection.createStatement(); RS = Stmt.executeQuery("desc " + instance_table); ResultSetMetaData rsMetaData = RS.getMetaData(); if (rsMetaData.getColumnCount() > 0) table_exists = true; RS.close(); Stmt.close(); } else { logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName()); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing Store " + ex); } try { //if the per-instance table doesn't exist, create it if (!table_exists) { logger.log(Level.INFO, "Creating Instance Table " + instance_table); if (dbm.getDatabaseProductName().equals("MySQL")) { Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String create_stmt = ""; create_stmt = "CREATE TABLE `" + this.instance_table + "` (" + "`crawl_set` decimal(19,5) NOT NULL," + "`insert_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP," + "`crawl_data` MEDIUMTEXT default NULL," + "PRIMARY KEY (`crawl_set`)," + "KEY `set_index` (`crawl_set`)" + ") ENGINE=MyISAM;"; statement.addBatch(create_stmt); statement.executeBatch(); statement.close(); } else { logger.log(Level.INFO, "Instance Table " + instance_table + " already exists"); //connection.close(); //TODO: somehow figure out if we should delete this table here } } boolean qrtz_table_exists = false; if (dbm.getDatabaseProductName().equals("MySQL")) { //check if the per-connector table exists logger.log(Level.FINE, "Checking to see if quartz tables exists..."); Stmt = connection.createStatement(); try { RS = Stmt.executeQuery("desc QRTZ_JOB_DETAILS"); ResultSetMetaData rsMetaData = RS.getMetaData(); if (rsMetaData.getColumnCount() > 0) qrtz_table_exists = true; } catch (Exception ex) { logger.log(Level.INFO, "Could not find Quartz Tables...creating now.."); } RS.close(); Stmt.close(); } else { logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName()); } if (!qrtz_table_exists) { logger.log(Level.INFO, "Creating Global Quartz Table "); //the quartz db setup scripts are at //quartz-1.8.0/docs/dbTables/tables_mysql.sql //one set of Quartz tables can handle any number of triggers/crons Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String create_stmt = "CREATE TABLE QRTZ_JOB_DETAILS (JOB_NAME VARCHAR(200) NOT NULL,JOB_GROUP VARCHAR(200) NOT NULL,DESCRIPTION VARCHAR(250) NULL,JOB_CLASS_NAME VARCHAR(250) NOT NULL,IS_DURABLE VARCHAR(1) NOT NULL,IS_VOLATILE VARCHAR(1) NOT NULL,IS_STATEFUL VARCHAR(1) NOT NULL,REQUESTS_RECOVERY VARCHAR(1) NOT NULL,JOB_DATA BLOB NULL,PRIMARY KEY (JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_JOB_LISTENERS ( JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, JOB_LISTENER VARCHAR(200) NOT NULL, PRIMARY KEY (JOB_NAME,JOB_GROUP,JOB_LISTENER), FOREIGN KEY (JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_FIRED_TRIGGERS ( ENTRY_ID VARCHAR(95) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, IS_VOLATILE VARCHAR(1) NOT NULL, INSTANCE_NAME VARCHAR(200) NOT NULL, FIRED_TIME BIGINT(13) NOT NULL, PRIORITY INTEGER NOT NULL, STATE VARCHAR(16) NOT NULL, JOB_NAME VARCHAR(200) NULL, JOB_GROUP VARCHAR(200) NULL, IS_STATEFUL VARCHAR(1) NULL, REQUESTS_RECOVERY VARCHAR(1) NULL, PRIMARY KEY (ENTRY_ID));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, IS_VOLATILE VARCHAR(1) NOT NULL, DESCRIPTION VARCHAR(250) NULL, NEXT_FIRE_TIME BIGINT(13) NULL, PREV_FIRE_TIME BIGINT(13) NULL, PRIORITY INTEGER NULL, TRIGGER_STATE VARCHAR(16) NOT NULL, TRIGGER_TYPE VARCHAR(8) NOT NULL, START_TIME BIGINT(13) NOT NULL, END_TIME BIGINT(13) NULL, CALENDAR_NAME VARCHAR(200) NULL, MISFIRE_INSTR SMALLINT(2) NULL, JOB_DATA BLOB NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_SIMPLE_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, REPEAT_COUNT BIGINT(7) NOT NULL, REPEAT_INTERVAL BIGINT(12) NOT NULL, TIMES_TRIGGERED BIGINT(10) NOT NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_CRON_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, CRON_EXPRESSION VARCHAR(200) NOT NULL, TIME_ZONE_ID VARCHAR(80), PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_BLOB_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, BLOB_DATA BLOB NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_TRIGGER_LISTENERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, TRIGGER_LISTENER VARCHAR(200) NOT NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_LISTENER), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_CALENDARS ( CALENDAR_NAME VARCHAR(200) NOT NULL, CALENDAR BLOB NOT NULL, PRIMARY KEY (CALENDAR_NAME));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS ( TRIGGER_GROUP VARCHAR(200) NOT NULL, PRIMARY KEY (TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_SCHEDULER_STATE ( INSTANCE_NAME VARCHAR(200) NOT NULL, LAST_CHECKIN_TIME BIGINT(13) NOT NULL, CHECKIN_INTERVAL BIGINT(13) NOT NULL, PRIMARY KEY (INSTANCE_NAME));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_LOCKS ( LOCK_NAME VARCHAR(40) NOT NULL, PRIMARY KEY (LOCK_NAME));"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('TRIGGER_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('JOB_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('CALENDAR_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('STATE_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('MISFIRE_ACCESS');"; statement.addBatch(create_stmt); statement.executeBatch(); statement.close(); } else { logger.log(Level.INFO, "Global Quartz Table already exists "); } connection.close(); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception Creating StoreTable " + ex); } }
From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java
@Test public void testTransaction() throws SQLException, IOException, ZooKeeperConnectionException, InterruptedException { stat.execute(DruidParserTestUtil.SEED[0]); TEST_UTIL.waitTableAvailable(Bytes.toBytes("User")); stat.execute(DruidParserTestUtil.SEED[1]); TEST_UTIL.waitTableAvailable(Bytes.toBytes("Photo")); conn.setAutoCommit(false);/*from w w w. ja va 2s . c o m*/ Statement stat = conn.createStatement(); stat.addBatch("Insert into User(user_id,name) values(1,'testTransaction');"); stat.addBatch("Insert into Photo(user_id,photo_id,tag) values(1,1,'tag');"); int[] ret = stat.executeBatch(); conn.commit(); int successNum = 0; for (int i : ret) { if (i == 1) successNum++; } assertTrue(successNum == 2); ResultSet rs = stat.executeQuery("SELECT * FROM User WHERE user_id=1"); assertTrue(rs.next()); assertTrue(rs.getString("name").equals("testTransaction")); rs = stat.executeQuery("SELECT * FROM Photo WHERE user_id=1 and photo_id=1"); assertTrue(rs.next()); assertTrue(rs.getString("tag").equals("tag")); }
From source file:com.edgenius.wiki.installation.DBLoader.java
public void resetDB(String type, ConnectionProxy con, String dbname, String username, String password) throws SQLException, IOException { Statement stat = null; try {/*from w w w . ja v a2s . co m*/ log.info("Reset database " + dbname + " starting..."); dbname = StringUtils.trimToEmpty(dbname); username = StringUtils.trimToEmpty(username); password = StringUtils.trimToEmpty(password); stat = con.createStatement(); List<String> lines = loadSQLFile(type, type + "-create-db.sql"); for (String sql : lines) { sql = sql.replaceAll("@TOKEN.DATABASE.NAME@", dbname); sql = sql.replaceAll("@TOKEN.DATABASE.USERNAME@", username); sql = sql.replaceAll("@TOKEN.DATABASE.PASSWORD@", password); stat.addBatch(sql); } stat.executeBatch(); log.info("Database " + dbname + " reset success"); } finally { if (stat != null) stat.close(); } }
From source file:com.autentia.tnt.bill.migration.BillToBillPaymentMigration.java
/** * executes an script received by parameter * @param script the script to be launched *//* w w w. jav a2 s . co m*/ private static void executeScript(String script) throws Exception { Connection con = null; Statement stmt = null; LineNumberReader file = null; String delimiter = ";"; try { log.debug("LOADING DATABASE SCRIPT" + script); // connect to database Class.forName(DATABASE_DRIVER); con = DriverManager.getConnection(DATABASE_CONNECTION, DATABASE_USER, DATABASE_PASS); //NOSONAR con.setAutoCommit(false); // DATABASE_PASS es nula stmt = con.createStatement(); // load file InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script); if (sqlScript == null) { throw new FileNotFoundException(script); } file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8")); // Add batched SQL sentences to statement StringBuilder sentence = new StringBuilder(); String line; while ((line = file.readLine()) != null) { line = line.trim(); if (!line.startsWith("--")) { // Interpret "DELIMITER" sentences if (line.trim().toUpperCase(Locale.ENGLISH).startsWith("DELIMITER")) { delimiter = line.trim().substring("DELIMITER".length()).trim(); } else { // Add line to sentence if (line.endsWith(delimiter)) { // Remove delimiter String lastLine = line.substring(0, line.length() - delimiter.length()); // Append line to sentence sentence.append(lastLine); // Execute sentence log.debug(" " + sentence.toString()); stmt.addBatch(sentence.toString()); // Prepare new sentence sentence = new StringBuilder(); } else { // Append line to sentence sentence.append(line); // Append separator for next line sentence.append(" "); } } } } // Execute batch log.debug("upgradeDatabase - executing batch of commands"); stmt.executeBatch(); // Commit transaction log.debug("upgradeDatabase - commiting changes to database"); con.commit(); // Report end of migration log.debug("END LOADING DATABASE SCRIPT"); } catch (Exception e) { log.error("FAILED: WILL BE ROLLED BACK: ", e); if (con != null) { con.rollback(); } } finally { cierraFichero(file); liberaConexion(con, stmt, null); } }
From source file:com.wso2telco.workflow.dao.WorkflowDbService.java
/** * Application entry./* ww w . j ava 2 s . c o m*/ * * @param applicationid the applicationid * @param operators the operators * @return the integer * @throws Exception the exception */ public void applicationEntry(int applicationid, Integer[] operators) throws SQLException, BusinessException { Connection con = null; Statement st = null; try { con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB); if (con == null) { throw new Exception("Connection not found"); } con.setAutoCommit(false); st = con.createStatement(); for (Integer d : operators) { if (!operatorAppsIsExist(applicationid, d)) { StringBuilder query = new StringBuilder(); query.append("INSERT INTO operatorapps (applicationid,operatorid) "); query.append("VALUES (" + applicationid + "," + d + ")"); st.addBatch(query.toString()); } } st.executeBatch(); con.commit(); } catch (SQLException e) { throw new SQLException(); } catch (Exception e) { throw new BusinessException(GenaralError.UNDEFINED); } finally { DbUtils.closeAllConnections(st, con, null); } }
From source file:com.flexive.ejb.beans.BriefcaseEngineBean.java
/** * {@inheritDoc}// w w w . j a v a 2 s .c om */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void remove(long id) throws FxApplicationException { // Lookup the briefcase Briefcase br = load(id); if (br == null) { throw new FxNotFoundException("ex.briefcase.notFound", ("#" + id)); } // Permission checks final UserTicket ticket = FxContext.getUserTicket(); if (!ticket.isGlobalSupervisor() && br.getMandator() != ticket.getMandatorId()) { if (!ticket.mayDeleteACL(br.getAcl(), br.getLifeCycleInfo().getCreatorId())) { throw new FxNotFoundException("ex.briefcase.noDeletePermission", br.getName()); } } // Delete operation Connection con = null; Statement stmt = null; try { // Obtain a database connection con = Database.getDbConnection(); stmt = con.createStatement(); stmt.addBatch("DELETE FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=" + id); stmt.addBatch("DELETE FROM " + TBL_BRIEFCASE_DATA + " WHERE briefcase_id=" + id); stmt.addBatch("DELETE FROM " + DatabaseConst.TBL_BRIEFCASE + " WHERE id=" + id); stmt.executeBatch(); } catch (SQLException exc) { throw new FxRemoveException(LOG, exc, "ex.briefcase.deleteFailed", br.getName()); } finally { closeObjects(BriefcaseEngineBean.class, con, stmt); } }
From source file:org.accada.epcis.repository.capture.CaptureOperationsModule.java
/** * Resets the database.//from w w w. j a va 2 s . c o m * * @throws SQLException * If something goes wrong resetting the database. * @throws IOException * If something goes wrong reading the reset script. * @throws UnsupportedOperationsException * If database resets are not allowed. */ public void doDbReset() throws SQLException, IOException { if (dbResetAllowed) { Session session = null; try { session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Connection connection = session.connection(); LOG.info("Running db reset script from file " + dbResetScript); Statement stmt = connection.createStatement(); BufferedReader reader = new BufferedReader(new FileReader(dbResetScript)); String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("--")) { LOG.debug("SQL: " + line); stmt.addBatch(line); } } stmt.executeBatch(); tx.commit(); } catch (Exception e) { LOG.error("dbReset failed: " + e.toString(), e); if (tx != null) { tx.rollback(); } throw new SQLException(e.toString()); } } finally { if (session != null) { session.close(); } } } else { throw new UnsupportedOperationException(); } }
From source file:com.wso2telco.workflow.dao.WorkflowDbService.java
/** * Insert operator app endpoints.// w ww.j ava2s . c o m * * @param appID the app id * @param opEndpointIDList the op endpoint id list * @throws Exception the exception */ public void insertOperatorAppEndpoints(int appID, int[] opEndpointIDList) throws SQLException, BusinessException { Connection con = null; Statement st = null; try { con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB); log.debug("opEndpointIDList.length : " + opEndpointIDList.length); con.setAutoCommit(false); st = con.createStatement(); for (int i = 0; i < opEndpointIDList.length; i++) { if (opEndpointIDList[i] > 0 && !endpointAppsIsExist(opEndpointIDList[i], appID)) { StringBuilder query = new StringBuilder(); query.append("INSERT INTO endpointapps (endpointid, applicationid, isactive) VALUES "); query.append("(" + opEndpointIDList[i] + "," + appID + ",0)"); st.addBatch(query.toString()); } } st.executeBatch(); con.commit(); } catch (SQLException e) { throw new SQLException(); } catch (Exception e) { throw new BusinessException(GenaralError.UNDEFINED); } finally { DbUtils.closeAllConnections(st, con, null); } }