List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.skilrock.lms.web.scratchService.orderMgmt.common.RequestApproveAction.java
/** * /*from www . ja v a2 s . co m*/ * This method is used to Deny the request from the Agent * * @author SkilRock Technologies * @Param * @Return String(SUCCESS or ERROR) throws LMSException */ public String Deny() throws LMSException { HttpSession session = getRequest().getSession(); orderId = ((Integer) session.getAttribute("OrgId")).intValue(); Connection conn = null; PreparedStatement pstmt1 = null; try { conn = DBConnect.getConnection(); conn.setAutoCommit(false); String query = QueryManager.getST5OrderRequest5Query(); // String query = "update st_se_bo_order set order_status='DENIED' // WHERE order_id=?"; pstmt1 = conn.prepareStatement(query); System.out.println("Query1 from Request Deny Action " + query); System.out.println("OrderId>>>>" + orderId); pstmt1.setInt(1, orderId); pstmt1.executeUpdate(); conn.commit(); return SUCCESS; } catch (SQLException se) { System.out.println("We got an exception while preparing a statement:" + "Probably bad SQL."); se.printStackTrace(); setRequestApproval("No"); throw new LMSException(se); } finally { try { if (pstmt1 != null) { pstmt1.close(); } if (conn != null) { conn.close(); } } catch (SQLException se) { throw new LMSException(se); } } }
From source file:com.skilrock.lms.web.scratchService.orderMgmt.common.RequestApproveAction.java
public String denyRetailer() throws LMSException { System.out.println("denie order for retailer"); HttpSession session = getRequest().getSession(); orderId = ((Integer) session.getAttribute("OrgId")).intValue(); Connection conn = null; PreparedStatement pstmt1 = null; try {//from ww w . j a v a2 s .com conn = DBConnect.getConnection(); conn.setAutoCommit(false); String query = QueryManager.getST5RetOrderRequest5Query(); // String query = "update st_se_bo_order set order_status='DENIED' // WHERE order_id=?"; pstmt1 = conn.prepareStatement(query); System.out.println("Query1 from Request Deny Action " + query); System.out.println("OrderId>>>>" + orderId); pstmt1.setInt(1, orderId); pstmt1.executeUpdate(); System.out.println(pstmt1); conn.commit(); return SUCCESS; } catch (SQLException se) { System.out.println("We got an exception while preparing a statement:" + "Probably bad SQL."); se.printStackTrace(); setRequestApproval("No"); throw new LMSException(se); } finally { try { if (pstmt1 != null) { pstmt1.close(); } if (conn != null) { conn.close(); } } catch (SQLException se) { throw new LMSException(se); } } }
From source file:com.wso2telco.dep.mediator.dao.USSDDAO.java
public void moUssdSubscriptionEntry(List<OperatorSubscriptionDTO> domainsubs, Integer moSubscriptionId) throws SQLException, Exception { Connection con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB); PreparedStatement insertStatement = null; try {// w w w . j a va 2s. c om if (con == null) { throw new Exception("Connection not found"); } con.setAutoCommit(false); StringBuilder queryString = new StringBuilder("INSERT INTO "); queryString.append(DatabaseTables.MO_USSD_SUBSCRIPTIONS.getTableName()); queryString.append(" (ussd_request_did, domainurl, operator) "); queryString.append("VALUES (?, ?, ?)"); insertStatement = con.prepareStatement(queryString.toString()); for (OperatorSubscriptionDTO d : domainsubs) { insertStatement.setInt(1, moSubscriptionId); insertStatement.setString(2, d.getDomain()); insertStatement.setString(3, d.getOperator()); insertStatement.addBatch(); } insertStatement.executeBatch(); con.commit(); } catch (SQLException e) { log.error("database operation error in operatorSubsEntry : ", e); throw e; } catch (Exception e) { log.error("error in operatorSubsEntry : ", e); throw e; } finally { DbUtils.closeAllConnections(insertStatement, con, null); } }
From source file:de.langmi.spring.batch.examples.readers.jdbc.JdbcPagingItemReaderTests.java
/** * Setup Datasource and create table for test. * * @throws Exception /* www. ja v a2s .c om*/ */ @Before public void setUp() throws Exception { // DataSource Setup, apache commons dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:mem:testdb"); dataSource.setUsername("sa"); dataSource.setPassword(""); // drop table if exists Connection conn = dataSource.getConnection(); Statement st = conn.createStatement(); st.execute(DROP_TEST_TABLE); conn.commit(); st.close(); conn.close(); // create table conn = dataSource.getConnection(); st = conn.createStatement(); st.execute(CREATE_TEST_TABLE); conn.commit(); st.close(); conn.close(); // fill with values conn = dataSource.getConnection(); // prevent auto commit for batching conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement(INSERT); // fill with values for (int i = 0; i < EXPECTED_COUNT; i++) { ps.setString(1, String.valueOf(i)); ps.addBatch(); } ps.executeBatch(); conn.commit(); ps.close(); conn.close(); }
From source file:assignment3.Populate.java
CreateUser() { try {//from w ww .ja va 2 s .c o m Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("JDBC Driver Missing"); e.printStackTrace(); return; } System.out.println("Oracle JDBC Driver Connected"); Connection conn = null; try { conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "MAYUR", "123456"); conn.setAutoCommit(false); PreparedStatement ps = conn .prepareStatement("insert into yelp_user values (?, ?, ?,?, ?, ?,?, ?, ?,?,?)"); JSONParser parser = new JSONParser(); Object obj = parser.parse(new BufferedReader(new FileReader( "C:\\Users\\mayur\\Downloads\\YelpDataset\\YelpDataset-CptS451\\yelp_user.json"))); //Object obj = parser.parse(new BufferedReader(new FileReader("C:\\Users\\mayur\\Downloads\\YelpDataset\\YelpDataset-CptS451\\yelp_user1.json"))); JSONArray jsonArray = (JSONArray) (obj); // JSONArray jsonArray = (JSONArray)(obj1); for (int i = 0; i < jsonArray.size(); i++) { JSONObject t = (JSONObject) jsonArray.get(i); String c = t.get("yelping_since").toString(); Date yelping_since = (Date) java.sql.Date.valueOf(c + "-01"); JSONObject votes = (JSONObject) t.get("votes"); // get all votes details Long votes_funny = (Long) votes.get("funny"); Long votes_useful = (Long) votes.get("useful"); Long votes_cool = (Long) votes.get("cool"); Long review_count = (Long) t.get("review_count"); String name = t.get("name").toString(); String user_id = t.get("user_id").toString(); JSONArray friends = (JSONArray) (t).get("friends"); int numfriends = 0; if (friends != null) { Iterator<String> iterator = friends.iterator(); ArrayList<String> friendid_list = new ArrayList<String>(); while (iterator.hasNext()) { friendid_list.add(iterator.next()); } if (friendid_list != null) numfriends = friendid_list.size(); friendid_list = null; iterator = null; } Long fans = (Long) t.get("fans"); double average_stars = (double) t.get("average_stars"); String type = t.get("type").toString(); ps.setDate(1, yelping_since); ps.setLong(2, votes_funny); ps.setLong(3, votes_useful); ps.setLong(4, votes_cool); ps.setLong(5, review_count); ps.setString(6, name); ps.setString(7, user_id); ps.setLong(8, fans); ps.setDouble(9, average_stars); ps.setString(10, type); ps.setInt(11, numfriends); ps.executeUpdate(); System.out.println("Record inserted " + i); } conn.commit(); ps.close(); } catch (Exception e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return; } }
From source file:com.excilys.ebi.bank.jdbc.SimpleBatchResourceDatabasePopulator.java
/** * Execute the given SQL script.//from w ww. j av a 2 s. com * <p> * The script will normally be loaded by classpath. There should be one * statement per line. Any {@link #setSeparator(String) statement * separators} will be removed. * <p> * <b>Do not use this method to execute DDL if you expect rollback.</b> * * @param connection * the JDBC Connection with which to perform JDBC operations * @param resource * the resource (potentially associated with a specific encoding) * to load the SQL script from * @param continueOnError * whether or not to continue without throwing an exception in * the event of an error * @param ignoreFailedDrops * whether of not to continue in the event of specifically an * error on a <code>DROP</code> */ private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError, boolean ignoreFailedDrops) throws SQLException, IOException { if (LOGGER.isInfoEnabled()) { LOGGER.info("Executing SQL script from " + resource); } long startTime = System.currentTimeMillis(); Iterator<String> statements = IOUtils.lineIterator(resource.getReader()); int lineNumber = 0; boolean initialAutoCommitState = connection.getAutoCommit(); connection.setAutoCommit(false); Statement stmt = connection.createStatement(); try { while (statements.hasNext()) { String statement = statements.next(); lineNumber++; try { stmt.addBatch(statement); if (lineNumber % batchSize == 0) { stmt.executeBatch(); connection.commit(); } } catch (SQLException ex) { boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop"); if (continueOnError || (dropStatement && ignoreFailedDrops)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Failed to execute SQL script statement at line " + lineNumber + " of resource " + resource + ": " + statement, ex); } } else { Exception nextException = ex.getNextException(); throw new ScriptStatementFailedException(statement, lineNumber, resource, nextException != null ? nextException : ex); } } } } finally { stmt.executeBatch(); connection.commit(); connection.setAutoCommit(initialAutoCommitState); try { stmt.close(); } catch (Throwable ex) { LOGGER.debug("Could not close JDBC Statement", ex); } } long elapsedTime = System.currentTimeMillis() - startTime; if (LOGGER.isInfoEnabled()) { LOGGER.info("Done executing SQL script from " + resource + " in " + elapsedTime + " ms."); } }
From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldDBDAO.java
@Override public synchronized void update(ExtendedField aExtendedField) { ArgumentNotValid.checkNotNull(aExtendedField, "aExtendedField"); Connection connection = HarvestDBConnection.get(); PreparedStatement statement = null; try {/*from ww w .ja v a2 s. c o m*/ final Long extendedfieldId = aExtendedField.getExtendedFieldID(); if (!exists(connection, extendedfieldId)) { throw new UnknownID("Extended Field id " + extendedfieldId + " is not known in persistent storage"); } connection.setAutoCommit(false); statement = connection.prepareStatement("" + "UPDATE extendedfield " + "SET extendedfield_id = ?, " + " extendedfieldtype_id = ?, " + " name = ?, " + " format = ?, " + " defaultvalue = ?, " + " options = ?, " + " datatype = ?, " + " mandatory = ?, " + " sequencenr = ?, " + " maxlen = ? " + "WHERE extendedfield_id = ? "); statement.setLong(1, aExtendedField.getExtendedFieldID()); statement.setLong(2, aExtendedField.getExtendedFieldTypeID()); statement.setString(3, aExtendedField.getName()); statement.setString(4, aExtendedField.getFormattingPattern()); statement.setString(5, aExtendedField.getDefaultValue()); statement.setString(6, aExtendedField.getOptions()); statement.setInt(7, aExtendedField.getDatatype()); // the following conversion from boolean to int is necessary, // because the database column 'mandatory' is a int field // and not a boolean (NAS-2127) statement.setInt(8, aExtendedField.isMandatory() ? 1 : 0); statement.setInt(9, aExtendedField.getSequencenr()); statement.setInt(10, aExtendedField.getMaxlen()); statement.setLong(11, aExtendedField.getExtendedFieldID()); //TODO log.debug(statement.toString()); statement.executeUpdate(); connection.commit(); } catch (SQLException e) { String message = "SQL error updating extendedfield " + aExtendedField + " in database" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.closeStatementIfOpen(statement); DBUtils.rollbackIfNeeded(connection, "update extendedfield", aExtendedField); HarvestDBConnection.release(connection); } }
From source file:com.glaf.core.jdbc.connection.DBCPConnectionProvider.java
public Connection getConnection() throws SQLException { Connection connection = null; int count = 0; while (count < conf.getInt("jdbc.connection.retryCount", 10)) { try {//from w ww. j av a 2 s . co m connection = ds.getConnection(); if (connection != null) { if (isolation != null) { connection.setTransactionIsolation(isolation.intValue()); } if (connection.getAutoCommit() != autocommit) { connection.setAutoCommit(autocommit); } return connection; } else { count++; try { Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500)); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (SQLException ex) { count++; try { Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500)); } catch (InterruptedException e) { e.printStackTrace(); } if (count >= conf.getInt("jdbc.connection.retryCount", 10)) { ex.printStackTrace(); throw ex; } } } return connection; }
From source file:com.autentia.tnt.manager.data.MigrationManager.java
/** * @return the original database version * @throws com.autentia.tnt.manager.data.exception.DataException *//*from w w w . j av a 2s .c o m*/ public Version upgradeDatabase() throws DataException { Version ret = null; Version db = null; Version code = Version.getApplicationVersion(); Session ses = HibernateUtil.getSessionFactory().openSession(); Connection con = ses.connection(); Statement stmt = null; LineNumberReader file = null; String delimiter = ";"; try { db = Version.getDatabaseVersion(); ret = db.clone(); log.info("upgradeDatabase - >>>> STARTING MIGRATION FROM " + db + " TO " + code + " <<<<"); // Disable auto-commit (just in case...) log.info("upgradeDatabase - disabling auto commit"); con.setAutoCommit(false); // Create statement stmt = con.createStatement(); // While necessary, upgrade database while (db.compareTo(code, Version.MINOR) < 0) { log.info("upgradeDatabase - " + db); // Compose script name and open it String script = SCRIPT_PREFIX + db.toString(Version.MINOR) + SCRIPT_SUFFIX; log.info("upgradeDatabase - loading script " + script); InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script); if (sqlScript == null) { throw FileNotFoundException(script); } file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8")); int _c; // 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.info(" " + 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.info("upgradeDatabase - executing batch of commands"); stmt.executeBatch(); // Re-read database version Version old = db; db = Version.getDatabaseVersion(con); if (old.equals(db)) { throw new DataException("Script was applied but did not upgrade database: " + script); } log.info("upgradeDatabase - database upgraded to version " + db); } // Commit transaction log.info("upgradeDatabase - commiting changes to database"); con.commit(); // Report end of migration log.info("upgradeDatabase - >>>> MIGRATION SUCCESSFULLY FINISHED <<<<"); } catch (Exception e) { log.error("upgradeDatabase - >>>> MIGRATION FAILED: WILL BE ROLLED BACK <<<<", e); try { con.rollback(); } catch (SQLException e2) { log.error("upgradeDatabase - Error al realizar el rollback"); } throw new DataException("Script was applied but did not upgrade database: ", e); } finally { if (file != null) { try { file.close(); } catch (IOException e2) { log.error("upgradeDatabase - Error al cerrar el fichero de script ", e2); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e2) { log.error("upgradeDatabase - Error al cerrar el statement"); } } ses.close(); } return ret; }
From source file:eionet.cr.dao.virtuoso.VirtuosoFolderDAO.java
public void createProjectBookmarksFolder(String projectName) throws DAOException { Connection sqlConn = null; RepositoryConnection repoConn = null; try {/* w w w . j av a 2s. c o m*/ sqlConn = SesameUtil.getSQLConnection(); sqlConn.setAutoCommit(false); repoConn = SesameUtil.getRepositoryConnection(); repoConn.setAutoCommit(false); ValueFactory vf = repoConn.getValueFactory(); List<Statement> statements = getProjectFolderCreationStatements(projectName, vf); repoConn.add(statements); repoConn.commit(); sqlConn.commit(); } catch (OpenRDFException e) { SesameUtil.rollback(repoConn); throw new DAOException(e.getMessage(), e); } catch (SQLException e) { SQLUtil.rollback(sqlConn); throw new DAOException(e.getMessage(), e); } finally { SQLUtil.close(sqlConn); SesameUtil.close(repoConn); } }