List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:jm.web.Archivo.java
/** * Guarda el registro del nombre y el archivo binario en una tabla de la base de datos. * @param nombre. Nombre del archivo subido. * @param archivo. Ruta del archivo subido. * @return Retorna true o false si se guarda o no el archivo en la DB. *//*from w w w.j a v a 2 s. com*/ public boolean setArchivoDB(String tabla, String campoNombre, String campoBytea, String clave, String nombre, File archivo) { boolean r = false; try { Connection conexion = this.getConexion(); PreparedStatement ps = conexion.prepareStatement("UPDATE " + tabla + " SET " + campoNombre + "='" + nombre + "', " + campoBytea + "=? WHERE " + tabla.replace("tbl_", "id_") + "=" + clave + ";"); conexion.setAutoCommit(false); FileInputStream archivoIS = new FileInputStream(this._archivo); try { /*ps.setBinaryStream(1, archivoIS, (int)archivo.length());*/ byte buffer[] = new byte[(int) archivo.length()]; archivoIS.read(buffer); ps.setBytes(1, buffer); ps.executeUpdate(); conexion.commit(); r = true; } catch (Exception e) { this._error = e.getMessage(); e.printStackTrace(); } finally { archivoIS.close(); ps.close(); } } catch (Exception e) { this._error = e.getMessage(); e.printStackTrace(); } return r; }
From source file:net.gcolin.simplerepo.search.SearchController.java
public void rebuild() throws IOException { if (running) { return;//from w w w. ja va 2 s . c om } running = true; configManager.setCurrentAction(REBUILD + "initialize"); nb = 0; try { final QueryRunner run = new QueryRunner(); try { Connection connection = null; try { connection = datasource.getConnection(); connection.setAutoCommit(false); run.update(connection, "delete from artifacttype"); run.update(connection, "delete from artifactversion"); run.update(connection, "delete from artifact"); run.update(connection, "update artifactindex set artifact=1,version=1"); connection.commit(); } catch (SQLException ex) { connection.rollback(); throw ex; } finally { DbUtils.close(connection); } } catch (SQLException ex) { logger.log(Level.SEVERE, null, ex); throw new IOException(ex); } for (final Repository repository : configManager.getConfiguration().getRepositories()) { File repo = new File(configManager.getRoot(), repository.getName()); if (repo.exists()) { Files.walkFileTree(repo.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { nb++; if (nb % 20 == 0) { configManager.setCurrentAction(REBUILD + " " + nb + " files"); } if (file.toString().endsWith(".pom")) { Model model = readPom(file.toFile()); add(repository, file.toFile(), model); } return FileVisitResult.CONTINUE; } }); } } } finally { running = false; configManager.setCurrentAction(null); } }
From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java
public void afterPropertiesSet() throws Exception { if (this.dataSource == null) { throw new IllegalArgumentException("dataSource should not be null"); }/* w w w . ja v a 2 s . c om*/ if (statements == null) { statements = new Statements(); statements.setStoreTableName(tableName); } Connection connection = null; boolean restoreAutoCommit = false; try { connection = getDataSource().getConnection(); if (connection.getAutoCommit()) { connection.setAutoCommit(false); restoreAutoCommit = true; } adapter = JDBCAdapterFactory.getAdapter(connection); if (statements == null) { statements = new Statements(); statements.setStoreTableName(tableName); } adapter.setStatements(statements); if (createDataBase) { adapter.doCreateTables(connection); } connection.commit(); } catch (SQLException e) { throw (IOException) new IOException("Exception while creating database").initCause(e); } finally { close(connection, restoreAutoCommit); } this.tccl = Thread.currentThread().getContextClassLoader(); }
From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java
public void exchangeSent(Exchange exchange) { try {// w ww . j av a2s .co m String id = exchange.getId(); Connection connection = null; boolean restoreAutoCommit = false; try { connection = dataSource.getConnection(); if (connection.getAutoCommit()) { connection.setAutoCommit(false); restoreAutoCommit = true; } store(connection, id, getDataForExchange(exchange)); connection.commit(); } finally { close(connection, restoreAutoCommit); } } catch (Exception e) { log.error("Could not persist exchange", e); } }
From source file:com.cloudera.sqoop.manager.OracleManagerTest.java
@Before public void setUp() { super.setUp(); SqoopOptions options = new SqoopOptions(OracleUtils.CONNECT_STRING, TABLE_NAME); OracleUtils.setOracleAuth(options);/*from w w w . ja va 2 s .co m*/ manager = new OracleManager(options); options.getConf().set("oracle.sessionTimeZone", "US/Pacific"); // Drop the existing table, if there is one. try { OracleUtils.dropTable(TABLE_NAME, manager); } catch (SQLException sqlE) { fail("Could not drop table " + TABLE_NAME + ": " + sqlE); } Connection connection = null; Statement st = null; try { connection = manager.getConnection(); connection.setAutoCommit(false); st = connection.createStatement(); // create the database table and populate it with data. st.executeUpdate("CREATE TABLE " + TABLE_NAME + " (" + "id INT NOT NULL, " + "name VARCHAR2(24) NOT NULL, " + "start_date DATE, " + "salary FLOAT, " + "dept VARCHAR2(32), " + "timestamp_tz TIMESTAMP WITH TIME ZONE, " + "timestamp_ltz TIMESTAMP WITH LOCAL TIME ZONE, " + "PRIMARY KEY (id))"); st.executeUpdate( "INSERT INTO " + TABLE_NAME + " VALUES(" + "1,'Aaron',to_date('2009-05-14','yyyy-mm-dd')," + "1000000.00,'engineering','29-DEC-09 12.00.00.000000000 PM'," + "'29-DEC-09 12.00.00.000000000 PM')"); st.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "2,'Bob',to_date('2009-04-20','yyyy-mm-dd')," + "400.00,'sales','30-DEC-09 12.00.00.000000000 PM'," + "'30-DEC-09 12.00.00.000000000 PM')"); st.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "3,'Fred',to_date('2009-01-23','yyyy-mm-dd'),15.00," + "'marketing','31-DEC-09 12.00.00.000000000 PM'," + "'31-DEC-09 12.00.00.000000000 PM')"); connection.commit(); } catch (SQLException sqlE) { LOG.error("Encountered SQL Exception: " + sqlE); sqlE.printStackTrace(); fail("SQLException when running test setUp(): " + sqlE); } finally { try { if (null != st) { st.close(); } if (null != connection) { connection.close(); } } catch (SQLException sqlE) { LOG.warn("Got SQLException when closing connection: " + sqlE); } } }
From source file:net.gcolin.simplerepo.search.SearchController.java
public SearchController(ConfigurationManager configManager) throws IOException { this.configManager = configManager; File plugins = new File(configManager.getRoot(), "plugins"); plugins.mkdirs();//w ww . ja v a2 s. co m System.setProperty("derby.system.home", plugins.getAbsolutePath()); BasicDataSource s = new BasicDataSource(); s.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); s.setUrl("jdbc:derby:search" + (new File(plugins, "search").exists() ? "" : ";create=true")); s.setUsername("su"); s.setPassword(""); s.setMaxTotal(10); s.setMinIdle(0); s.setDefaultAutoCommit(true); datasource = s; Set<String> allTables = new HashSet<>(); Connection connection = null; try { try { connection = datasource.getConnection(); connection.setAutoCommit(false); DatabaseMetaData dbmeta = connection.getMetaData(); try (ResultSet rs = dbmeta.getTables(null, null, null, new String[] { "TABLE" })) { while (rs.next()) { allTables.add(rs.getString("TABLE_NAME").toLowerCase()); } } if (!allTables.contains("artifact")) { QueryRunner run = new QueryRunner(); run.update(connection, "CREATE TABLE artifactindex(artifact bigint NOT NULL, version bigint NOT NULL)"); run.update(connection, "INSERT INTO artifactindex (artifact,version) VALUES (?,?)", 1L, 1L); run.update(connection, "CREATE TABLE artifact(id bigint NOT NULL,groupId character varying(120), artifactId character varying(120),CONSTRAINT artifact_pkey PRIMARY KEY (id))"); run.update(connection, "CREATE TABLE artifactversion(artifact_id bigint NOT NULL,id bigint NOT NULL," + "version character varying(100)," + "reponame character varying(30)," + "CONSTRAINT artifactversion_pkey PRIMARY KEY (id)," + "CONSTRAINT fk_artifactversion_artifact_id FOREIGN KEY (artifact_id) REFERENCES artifact (id) )"); run.update(connection, "CREATE TABLE artifacttype(version_id bigint NOT NULL,packaging character varying(20) NOT NULL,classifier character varying(30)," + "CONSTRAINT artifacttype_pkey PRIMARY KEY (version_id,packaging,classifier)," + "CONSTRAINT fk_artifacttype_version FOREIGN KEY (version_id) REFERENCES artifactversion (id))"); run.update(connection, "CREATE INDEX artifactindex ON artifact(groupId,artifactId)"); run.update(connection, "CREATE INDEX artifactgroupindex ON artifact(groupId)"); run.update(connection, "CREATE INDEX artifactversionindex ON artifactversion(version)"); } connection.commit(); } catch (SQLException ex) { connection.rollback(); throw ex; } finally { DbUtils.close(connection); } } catch (SQLException ex) { throw new IOException(ex); } }
From source file:gov.nih.nci.migration.MigrationDriver.java
private void encryptDecryptUserInformation() throws EncryptionException, SQLException { Connection connection = getConnection(); //Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); connection.setAutoCommit(false); ResultSet resultSet = null;// ww w . j a v a 2 s .c o m if ("oracle".equals(DATABASE_TYPE)) { //resultSet = stmt.executeQuery("SELECT CSM_USER.* FROM CSM_USER FOR UPDATE"); resultSet = stmt.executeQuery("SELECT CSM_USER.* FROM CSM_USER"); } else { resultSet = stmt.executeQuery("SELECT * FROM CSM_USER"); } String userPassword = null; String firstName = null; String lastName = null; String organization = null; String department = null; String title = null; String phoneNumber = null; String emailId = null; String encryptedUserPassword = null; Date expiryDate = null; while (resultSet.next()) { userPassword = resultSet.getString("PASSWORD"); firstName = resultSet.getString("FIRST_NAME"); lastName = resultSet.getString("LAST_NAME"); organization = resultSet.getString("ORGANIZATION"); department = resultSet.getString("DEPARTMENT"); title = resultSet.getString("TITLE"); phoneNumber = resultSet.getString("PHONE_NUMBER"); emailId = resultSet.getString("EMAIL_ID"); if (!StringUtilities.isBlank(userPassword)) { String orgPasswordStr = desEncryption.decrypt(userPassword); encryptedUserPassword = aesEncryption.encrypt(orgPasswordStr); if (!StringUtilities.isBlank(encryptedUserPassword)) { resultSet.updateString("PASSWORD", encryptedUserPassword); } } if (!StringUtilities.isBlank(firstName)) resultSet.updateString("FIRST_NAME", aesEncryption.encrypt(firstName)); if (!StringUtilities.isBlank(lastName)) resultSet.updateString("LAST_NAME", aesEncryption.encrypt(lastName)); if (!StringUtilities.isBlank(organization)) resultSet.updateString("ORGANIZATION", aesEncryption.encrypt(organization)); if (!StringUtilities.isBlank(department)) resultSet.updateString("DEPARTMENT", aesEncryption.encrypt(department)); if (!StringUtilities.isBlank(title)) resultSet.updateString("TITLE", aesEncryption.encrypt(title)); if (!StringUtilities.isBlank(phoneNumber)) resultSet.updateString("PHONE_NUMBER", aesEncryption.encrypt(phoneNumber)); if (!StringUtilities.isBlank(emailId)) resultSet.updateString("EMAIL_ID", aesEncryption.encrypt(emailId)); expiryDate = DateUtils.addDays(Calendar.getInstance().getTime(), Integer.parseInt(getExpiryDays())); resultSet.updateDate("PASSWORD_EXPIRY_DATE", new java.sql.Date(expiryDate.getTime())); System.out.println("Updating user:" + resultSet.getString("LOGIN_NAME")); resultSet.updateRow(); } connection.commit(); }
From source file:de.langmi.spring.batch.examples.readers.support.CompositeCursorItemReaderTest.java
/** * Create a table and fill with some test data. * * @param dataSource//from w w w . jav a 2 s. c o m * @throws Exception */ private void createTableWithTestData(final DataSource dataSource) throws Exception { // create table Connection conn = dataSource.getConnection(); Statement 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:com.ibm.research.rdf.store.cmd.AbstractRdfCommand.java
private Connection getConnection() { String backend = params.get("-backend"); String db = params.get("-db"); String port = params.get("-port"); String host = params.get("-host"); String user = params.get("-user"); String password = params.get("-password"); if (backend == null) backend = Store.Backend.db2.name(); if (host == null) host = "localhost"; if (port == null) port = "50000"; String JDBC_URL;//w ww . j a v a2 s . co m String classNameString; if (backend.equalsIgnoreCase(Store.Backend.postgresql.name())) { JDBC_URL = new String("jdbc:postgresql://" + host + ":" + port + "/" + db); classNameString = new String("org.postgresql.Driver"); } else if (backend.equalsIgnoreCase(Store.Backend.shark.name())) { JDBC_URL = new String("jdbc:hive2://" + host + ":" + port + "/" + db); classNameString = new String("org.apache.hive.jdbc.HiveDriver"); } else { JDBC_URL = new String("jdbc:db2://" + host + ":" + port + "/" + db); classNameString = new String("com.ibm.db2.jcc.DB2Driver"); } try { Class.forName(classNameString); Connection conn = DriverManager.getConnection(JDBC_URL, user, password); if (conn != null) { if (!backend.equalsIgnoreCase(Store.Backend.shark.name())) { // this will cause StoreManager to start a txn // and commit on success, which is good for us conn.setAutoCommit(true); } } else { System.err.println("Failed to establish connection to the database"); } return conn; } catch (ClassNotFoundException e) { System.err.println(e.getLocalizedMessage()); return null; } catch (SQLException e) { System.err.println(e.getLocalizedMessage()); return null; } // + ":traceFile=c:/jcc.log;traceLevel=-1;traceFileAppend=false;" ; }
From source file:hoot.services.db.DbUtils.java
/** * Clears all data in all resource related tables in the database * * @param conn JDBC Connection/* ww w .j a v a 2s .c o m*/ * @throws Exception * if any records still exist in the table after the attempted * deletion */ public static void clearServicesDb(Connection conn) throws Exception { try { deleteMapRelatedTables(); conn.setAutoCommit(false); Configuration configuration = getConfiguration(); SQLDeleteClause delete = new SQLDeleteClause(conn, configuration, QCurrentWayNodes.currentWayNodes); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QCurrentRelationMembers.currentRelationMembers); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QCurrentNodes.currentNodes); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QCurrentWays.currentWays); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QCurrentRelations.currentRelations); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QChangesets.changesets); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QMaps.maps); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QUsers.users); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QReviewItems.reviewItems); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QElementIdMappings.elementIdMappings); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QReviewMap.reviewMap); delete.execute(); delete = new SQLDeleteClause(conn, configuration, QJobStatus.jobStatus); delete.execute(); conn.commit(); } catch (Exception e) { conn.rollback(); String msg = "Error clearing services database. "; msg += " " + e.getCause().getMessage(); throw new Exception(msg); } finally { conn.setAutoCommit(true); } }