List of usage examples for java.sql Connection commit
void commit() throws SQLException;
Connection
object. From source file:com.l2jserver.service.database.sql.AbstractSQLDatabaseService.java
@Override public int transaction(TransactionExecutor executor) { Preconditions.checkNotNull(executor, "executor"); try {//from w ww.j a va2 s . c o m final Connection conn = dataSource.getConnection(); log.debug("Executing transaction {} with {}", executor, conn); try { conn.setAutoCommit(false); transaction.set(new TransactionIsolatedConnection(conn)); final int rows = executor.perform(); conn.commit(); return rows; } catch (Exception e) { conn.rollback(); throw e; } finally { transaction.set(null); transaction.remove(); conn.setAutoCommit(true); conn.close(); } } catch (DatabaseException e) { throw e; } catch (Throwable e) { throw new DatabaseException(e); } }
From source file:com.che.software.testato.domain.dao.jdbc.impl.MatrixResultDAO.java
/** * Creates the matrix results for a given iteration assignment. The related * matrix must be completed before calling this method. * // ww w . java 2 s .c o m * @author Clement HELIOU (clement.heliou@che-software.com). * @param iterationId the given iteration id. * @since August, 2011. * @throws MatrixResultCreationDAOException if an error occurs during the * creation. */ @Override public void createMatrixResults(int iterationId) throws MatrixResultCreationDAOException { LOGGER.debug("createMatrixResults(" + iterationId + ")."); Connection connection = null; try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); for (MatrixResult result : getQueryRunner().query(connection, "SELECT first_script AS scriptId, iteration_assignment_id AS iterationAssignmentId, ((SUM((value/( SELECT SUM(value) FROM comparisonMatrixItem WHERE iteration_assignment_id = ? AND second_script = base.second_script GROUP BY second_script ORDER BY second_script ))))/COUNT(*))::numeric(15,2) AS percentage FROM comparisonMatrixItem base WHERE iteration_assignment_id = ? GROUP BY first_script,iteration_assignment_id ORDER BY first_script ", new BeanListHandler<MatrixResult>(MatrixResult.class), new Object[] { iterationId, iterationId })) { getQueryRunner().update(connection, "INSERT INTO iteration_assignment_source_script(script_id, iteration_assignment_id, percentage) VALUES(?, ?, ?) ", new Object[] { result.getScriptId(), result.getIterationAssignmentId(), result.getPercentage() }); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new MatrixResultCreationDAOException(e1); } throw new MatrixResultCreationDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramProfilingMessageSymbolSqlAdapter.java
public ProgramProfilingMessageSymbol createNewProfilingMessageSymbol(int configID, int programMessageSymbolID) throws AdaptationException { ProgramProfilingMessageSymbol profilingMessageSymbol = null; Connection connection = null; Statement statement = null;/*from w w w. java2s .co m*/ ResultSet resultSet = null; try { String query = "INSERT INTO ProgramProfilingMessageSymbols" + "(projectDeploymentConfigurationID, programMessageSymbolID)" + " VALUES (" + configID + ", " + programMessageSymbolID + ")"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM ProgramProfilingMessageSymbols WHERE " + "projectDeploymentConfigurationID = " + configID + " AND " + "programMessageSymbolID = " + programMessageSymbolID; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create program profiling message " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingMessageSymbol = getProfilingMessageSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createNewProfilingMessageSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return profilingMessageSymbol; }
From source file:net.sf.jabref.sql.exporter.DBExporter.java
/** * Accepts the BibDatabase and MetaData, generates the DML required to create and populate SQL database tables, * and writes this DML to the specified SQL database. * * @param database The BibDatabase to export * @param metaData The MetaData object containing the groups information * @param keySet The set of IDs of the entries to export. * @param databaseStrings The necessary database connection information *//* w w w . ja v a2 s .c om*/ public void exportDatabaseToDBMS(final BibDatabase database, final MetaData metaData, Set<String> keySet, DBStrings databaseStrings, JabRefFrame frame) throws Exception { String dbName; Connection conn = null; boolean redisplay = false; try { conn = this.connectToDB(databaseStrings); createTables(conn); Vector<Vector<String>> matrix = createExistentDBNamesMatrix(databaseStrings); DBImportExportDialog dialogo = new DBImportExportDialog(frame, matrix, DBImportExportDialog.DialogType.EXPORTER); if (dialogo.removeAction) { dbName = getDBName(matrix, databaseStrings, frame, dialogo); removeDB(dialogo, dbName, conn, metaData); redisplay = true; } else if (dialogo.hasDBSelected) { dbName = getDBName(matrix, databaseStrings, frame, dialogo); performExport(database, metaData, keySet, conn, dbName); } if (!conn.getAutoCommit()) { conn.commit(); conn.setAutoCommit(true); } if (redisplay) { exportDatabaseToDBMS(database, metaData, keySet, databaseStrings, frame); } } catch (SQLException ex) { if ((conn != null) && !conn.getAutoCommit()) { conn.rollback(); } throw ex; } finally { if (conn != null) { conn.close(); } } }
From source file:dk.netarkivet.harvester.datamodel.GlobalCrawlerTrapListDBDAO.java
/** * Update a trap list. In order to update the trap expressions for this * list, we first delete all the existing trap expressions for the list * then add all those in the updated version. * @param trapList the trap list to update *///from w w w . j a va 2s. c o m @Override public void update(GlobalCrawlerTrapList trapList) { ArgumentNotValid.checkNotNull(trapList, "trapList"); Connection conn = HarvestDBConnection.get(); PreparedStatement stmt = null; try { conn.setAutoCommit(false); stmt = conn.prepareStatement(LIST_UPDATE_STMT); stmt.setString(1, trapList.getName()); stmt.setString(2, trapList.getDescription()); stmt.setBoolean(3, trapList.isActive()); stmt.setInt(4, trapList.getId()); stmt.executeUpdate(); stmt.close(); //Delete all the trap expressions. stmt = conn.prepareStatement(DELETE_EXPR_STMT); stmt.setInt(1, trapList.getId()); stmt.executeUpdate(); stmt.close(); // Add the new trap expressions one by one. for (String expr : trapList.getTraps()) { stmt = conn.prepareStatement(INSERT_TRAP_EXPR_STMT); stmt.setInt(1, trapList.getId()); stmt.setString(2, expr); stmt.executeUpdate(); stmt.close(); } conn.commit(); } catch (SQLException e) { String message = "Error updating trap list :'" + trapList.getId() + "'\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new UnknownID(message, e); } finally { DBUtils.closeStatementIfOpen(stmt); DBUtils.rollbackIfNeeded(conn, "update trap list", trapList); HarvestDBConnection.release(conn); } }
From source file:com.wso2telco.workflow.dao.WorkflowDbService.java
/** * Insert operator app endpoints./* ww w . j av a2 s.com*/ * * @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); } }
From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java
/** * ?// ww w.jav a 2 s. c om * @param list sql? */ public void executeBatchByPrepare(String sql, final List<String> list) { Connection conn = null; PreparedStatement st = null; try { conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection(); conn.setAutoCommit(false); // ?? st = conn.prepareStatement(sql); for (int i = 1, j = list.size(); i < j; i++) { Object objs = list.get(i - 1); if (objs instanceof List) { List<Object> values = (List<Object>) objs; for (int h = 1, k = values.size(); h <= k; k++) { Object value = values.get(k - 1); setParameters(st, k, value); } } else { setParameters(st, i, objs); } st.addBatch(sql); if (i % 240 == 0) {//?240?sql??? st.executeBatch(); conn.commit(); st.clearBatch(); } else if (i % j == 0) {//?? st.executeBatch(); conn.commit(); st.clearBatch(); } } } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { closeAll(st, conn); } }
From source file:com.glaf.core.startup.DBUpdateThread.java
public void run() { logger.debug("->jdbc url:" + props.getProperty(DBConfiguration.JDBC_URL)); FileExecutionHelper helper = new FileExecutionHelper(); Connection conn = null; Statement stmt = null;//from w ww . ja v a 2 s .c o m try { conn = DBConnectionFactory.getConnection(props); if (conn != null) { helper.createTable(conn); String path = SystemProperties.getConfigRootPath() + "/conf/bootstrap/update"; File dir = new File(path); File contents[] = dir.listFiles(); if (contents != null) { for (int i = 0; i < contents.length; i++) { if (contents[i].isFile() && StringUtils.endsWith(contents[i].getName(), ".sql")) { try { if (!helper.exists(conn, "update_sql", contents[i])) { long lastModified = helper.lastModified(conn, "update_sql", contents[i]); if (contents[i].lastModified() > lastModified) { conn.setAutoCommit(false); String ddlStatements = FileUtils.readFile(contents[i].getAbsolutePath()); DBUtils.executeSchemaResourceIgnoreException(conn, ddlStatements); helper.save(conn, "update_sql", contents[i]); conn.commit(); } } } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } } } } } } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } finally { JdbcUtils.close(stmt); JdbcUtils.close(conn); } }
From source file:consultor.CSVLoader.java
/** * Parse CSV file using OpenCSV library and load in * given database table. /*from ww w .j a v a 2 s . com*/ * @param csvFile Input CSV file * @param tableName Database table name to import data * @param truncateBeforeLoad Truncate the table before inserting * new records. * @throws Exception */ public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad) throws Exception { CSVReader csvReader = null; if (null == this.connection) { throw new Exception("Not a valid connection."); } try { csvReader = new CSVReader(new FileReader(csvFile), this.seprator); } catch (Exception e) { e.printStackTrace(); throw new Exception("Error occured while executing file. " + e.getMessage()); } String[] headerRow = csvReader.readNext(); if (null == headerRow) { throw new FileNotFoundException( "No columns defined in given CSV file." + "Please check the CSV file format."); } String questionmarks = StringUtils.repeat("?,", headerRow.length); questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1); String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName); query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ",")); query = query.replaceFirst(VALUES_REGEX, questionmarks); System.out.println("Query: " + query); String[] nextLine; Connection con = null; PreparedStatement ps = null; try { con = this.connection; con.setAutoCommit(false); ps = con.prepareStatement(query); if (truncateBeforeLoad) { //delete data from table before loading csv con.createStatement().execute("DELETE FROM " + tableName); } final int batchSize = 1000; int count = 0; Date date = null; while ((nextLine = csvReader.readNext()) != null) { if (null != nextLine) { int index = 1; for (String string : nextLine) { date = DateUtil.convertToDate(string); if (null != date) { ps.setDate(index++, new java.sql.Date(date.getTime())); } else { ps.setString(index++, string); } } ps.addBatch(); } if (++count % batchSize == 0) { ps.executeBatch(); } } ps.executeBatch(); // insert remaining records con.commit(); } catch (Exception e) { con.rollback(); e.printStackTrace(); throw new Exception("Error occured while loading data from file to database." + e.getMessage()); } finally { if (null != ps) ps.close(); if (null != con) con.close(); csvReader.close(); } }
From source file:edu.clemson.cs.nestbed.server.adaptation.sql.MoteDeploymentConfigurationSqlAdapter.java
public MoteDeploymentConfiguration addMoteDeploymentConfiguration(int projectDepConfID, int moteID, int programID, int radioPowerLevel) throws AdaptationException { MoteDeploymentConfiguration mdc = null; Connection connection = null; Statement statement = null;/* w w w. j a v a 2s . co m*/ ResultSet resultSet = null; try { String query = "INSERT INTO MoteDeploymentConfigurations(" + "projectDeploymentConfigurationID, " + "moteID, programID, radioPowerLevel) VALUES (" + projectDepConfID + ", " + moteID + ", " + programID + ", " + radioPowerLevel + ")"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from MoteDeploymentConfigurations WHERE " + "projectDeploymentConfigurationID = " + projectDepConfID + " AND moteID = " + moteID; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Unable to select newly added config."; log.error(msg); ; throw new AdaptationException(msg); } mdc = getMoteDeploymentConfiguration(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in addMoteDeploymentConfiguration"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return mdc; }