List of usage examples for java.sql Connection commit
void commit() throws SQLException;
Connection
object. From source file:com.cloudera.sqoop.testutil.BaseSqoopTestCase.java
/** * Drop a table if it already exists in the database. * @param table the name of the table to drop. * @throws SQLException if something goes wrong. *//* ww w. j a va2 s .com*/ protected void dropTableIfExists(String table) throws SQLException { Connection conn = getManager().getConnection(); PreparedStatement statement = conn.prepareStatement("DROP TABLE " + table + " IF EXISTS", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); try { statement.executeUpdate(); conn.commit(); } finally { statement.close(); } }
From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java
@Override public Files getFileById(Long id) { Connection con = null; PreparedStatement statement = null; String sql = "select * from " + Files.FilesFieldsKey.TABLE + " where id=?"; Files fStat = new Files(); try {//from ww w . j a va2s. c o m con = DBConnector.getConnection(); con.setAutoCommit(false); statement = con.prepareStatement(sql); statement.setLong(1, id); ResultSet rs = statement.executeQuery(); ResultSetToFiles(rs, fStat); con.commit(); } catch (SQLException e) { handleException(e, con); } finally { doFinal(con, statement); } return fStat; }
From source file:org.ulyssis.ipp.processor.Processor.java
private void trySpawnReaderListener(int readerId) { URI uri = Config.getCurrentConfig().getReader(readerId).getURI(); String updateChannel = JedisHelper.dbLocalChannel(Config.getCurrentConfig().getUpdateChannel(), uri); try {// w w w. j av a 2s. c o m Optional<Long> lastUpdate; { Connection connection = null; try { connection = Database.createConnection(EnumSet.of(READ_ONLY)); lastUpdate = getLastUpdateForReader(connection, readerId); connection.commit(); } catch (SQLException e) { if (connection != null) connection.rollback(); throw e; } finally { if (connection != null) { connection.close(); } } } Jedis subJedis = JedisHelper.get(uri); ReaderListener listener = new ReaderListener(readerId, this::queueEvent, lastUpdate); readerListeners.add(listener); Thread thread = new Thread(() -> { try { LOG.info("Reader listener {} subscribing to channel {} on uri {}", readerId, updateChannel, uri); subJedis.subscribe(listener, updateChannel); } catch (JedisConnectionException e) { LOG.error( "Reader listener {} stopped (uri: {}) because of a connection failure, scheduling reconnect", readerId, uri, e); executorService.schedule(() -> trySpawnReaderListener(readerId), 5L, TimeUnit.SECONDS); } }); threads.add(thread); thread.start(); } catch (SQLException e) { LOG.error("Error fetching last update for reader {} from database, scheduling retry", readerId, e); executorService.schedule(() -> trySpawnReaderListener(readerId), 5L, TimeUnit.SECONDS); } catch (JedisConnectionException e) { LOG.error("Couldn't connect to reader {}, uri {}, scheduling reconnect", readerId, uri, e); executorService.schedule(() -> trySpawnReaderListener(readerId), 5L, TimeUnit.SECONDS); } }
From source file:com.moss.blankslate.MsSqlServerCatalogFactory.java
public synchronized BlankslateCatalogHandle createCatalog(boolean deleteOnExit) throws Exception { checkConfig();/*from w w w .j av a2 s .c om*/ String testCatalogName = "test-" + sequenceNum + "-" + getCatalogNameQualifier(); synchronized (sequenceNum) { sequenceNum++; } JdbcConnectionConfig config = new JdbcConnectionConfig(DatabaseType.DB_TYPE_SQL_SERVER, null, hostname, null, "master", login, password); Connection adminConnection = config.createConnection(); try { adminConnection.createStatement().execute("use \"" + testCatalogName + "\""); log.info("Database \"" + testCatalogName + "\" already exists... will be deleted"); try { adminConnection.createStatement().execute("use master"); adminConnection.createStatement().execute("drop database \"" + testCatalogName + "\""); } catch (Exception e) { e.printStackTrace(); throw (e); } adminConnection.commit(); } catch (Exception err) { } adminConnection.createStatement().execute("create database \"" + testCatalogName + "\""); adminConnection.close(); JdbcConnectionConfig newCatalogConfig = new JdbcConnectionConfig(DatabaseType.DB_TYPE_SQL_SERVER, null, hostname, null, testCatalogName, login, password); BlankslateCatalogHandle handle = new BlankslateCatalogHandle(testCatalogName, newCatalogConfig, "dbo"); return handle; }
From source file:au.com.ish.derbydump.derbydump.main.DumpTest.java
@Test public void theDumpTest() throws Exception { // Create table StringBuilder createTableBuffer = new StringBuilder(); createTableBuffer.append("CREATE TABLE "); createTableBuffer.append(Configuration.getConfiguration().getSchemaName()); createTableBuffer.append("."); createTableBuffer.append(tableName); createTableBuffer.append(" ("); StringBuilder insertBuffer = new StringBuilder(); insertBuffer.append("INSERT INTO "); insertBuffer.append(RESOURCE_SCHEMA_NAME); insertBuffer.append("."); insertBuffer.append(tableName);//from w w w . j av a2s. c o m insertBuffer.append(" VALUES ("); for (String col : columns) { createTableBuffer.append(col.toUpperCase()); //String[] c = col.split(" "); //insertBuffer.append(c[0].toUpperCase().trim()); insertBuffer.append("?"); if (!columns[columns.length - 1].equals(col)) { createTableBuffer.append(", "); insertBuffer.append(","); } } createTableBuffer.append(")"); insertBuffer.append(")"); config.setTableRewriteProperty("testSkip", "--exclude--"); config.setTableRewriteProperty("testRename", "testRenameNew"); config.setTruncateTables(truncate); File f = new File("./build/outputs/" + tableName + ".sql"); if (f.exists()) { f.delete(); } f.mkdirs(); config.setOutputFilePath(f.getCanonicalPath()); Connection connection = db.createNewConnection(); Statement statement = connection.createStatement(); PreparedStatement ps = null; try { statement.execute(createTableBuffer.toString()); connection.commit(); //config.setTableRewriteProperty("TABLE2", "--exclude--"); for (Object o : valuesToInsert) { Object[] vals = (Object[]) o; if (vals.length > 0) { ps = db.getConnection().prepareStatement(insertBuffer.toString()); for (int i = 0; i < vals.length; i++) { if (vals[i] instanceof InputStream) { ps.setBinaryStream(i + 1, (InputStream) vals[i]); } else { ps.setObject(i + 1, vals[i]); } } ps.execute(); connection.commit(); } } OutputThread output = new OutputThread(); Thread writer = new Thread(output, "File_Writer"); writer.start(); new DatabaseReader(output); // Let the writer know that no more data is coming writer.interrupt(); writer.join(); // Now let's read the output and see what is in it List<String> lines = FileUtils.readLines(f); assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 0;", lines.get(0)); assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 1;", lines.get(lines.size() - 1)); if (!skipped) { assertTrue("LOCK missing", lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;")); assertTrue("UNLOCK missing", lines.contains("UNLOCK TABLES;")); int index = lines.indexOf("LOCK TABLES `" + outputTableName + "` WRITE;"); if (truncate) { assertTrue("TRUNCATE missing", lines.contains("TRUNCATE TABLE " + outputTableName + ";")); assertTrue("INSERT missing, got " + lines.get(index + 2), lines.get(index + 2).startsWith("INSERT INTO " + outputTableName)); } else { assertTrue("INSERT missing, got " + lines.get(index + 1), lines.get(index + 1).startsWith("INSERT INTO " + outputTableName)); } for (String s : validOutputs) { assertTrue("VALUES missing :" + s, lines.contains(s)); } } else { assertTrue("LOCK missing", !lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;")); } } catch (Exception e) { e.printStackTrace(); fail("failed to create test data" + e.getMessage()); } finally { if (ps != null) { ps.close(); } statement.close(); connection.close(); } }
From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java
@Override public void insertIdeaInstance(IdeaInstance ideainstance) { PreparedStatement stat = null; Connection conn = null; try {// ww w . j a v a 2 s. c om conn = this.getConnection(); conn.setAutoCommit(false); this.insertIdeaInstance(ideainstance, conn); this.insertIdeaInstanceGroups(ideainstance.getCode(), ideainstance.getGroups(), conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error("Error creating ideainstance", t); throw new RuntimeException("Error creating ideainstance", t); } finally { this.closeDaoResources(null, stat, conn); } }
From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java
@Override public void updateIdeaInstance(IdeaInstance ideainstance) { PreparedStatement stat = null; Connection conn = null; try {//ww w . ja v a 2 s. co m conn = this.getConnection(); conn.setAutoCommit(false); this.updateIdeaInstance(ideainstance, conn); this.insertIdeaInstanceGroups(ideainstance.getCode(), ideainstance.getGroups(), conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error("Error updating ideainstance", t); throw new RuntimeException("Error updating ideainstance", t); } finally { this.closeDaoResources(null, stat, conn); } }
From source file:com.splicemachine.derby.test.framework.SpliceIndexWatcher.java
@Override public void starting(Description description) { LOG.trace("Starting"); Connection connection = null; PreparedStatement statement = null; Statement statement2 = null;//from w ww . j a v a2 s . com ResultSet rs = null; try { connection = SpliceNetConnection.getConnection(); statement = connection.prepareStatement(SELECT_SPECIFIC_INDEX); statement.setString(1, indexSchemaName); statement.setString(2, indexName); rs = statement.executeQuery(); if (rs.next()) { executeDrop(connection, indexSchemaName, indexName); } connection.commit(); statement2 = connection.createStatement(); statement2.execute(String.format("%s index %s.%s on %s.%s %s", create, indexSchemaName, indexName, tableSchemaName, tableName, createString)); connection.commit(); } catch (Exception e) { LOG.error("Create index statement is invalid "); throw new RuntimeException(e); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(statement); DbUtils.closeQuietly(statement2); DbUtils.commitAndCloseQuietly(connection); } super.starting(description); }
From source file:mx.com.pixup.portal.dao.FormaPagoDaoJdbc.java
@Override public FormaPago insertFormaPago(FormaPago formaPago) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null;/* www. j a v a 2 s .co m*/ String sql = "insert into forma_pago (descripcion) values (?)"; try { connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, formaPago.getDescripcion()); preparedStatement.execute(); connection.commit(); resultSet = preparedStatement.getGeneratedKeys(); resultSet.next(); formaPago.setId(resultSet.getInt(1)); return formaPago; } catch (Exception e) { } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } return null; }
From source file:com.mirth.connect.server.controllers.tests.TestUtils.java
public static void fixMessageIdSequence(String channelId) throws Exception { Connection connection = null; long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId); String database = (String) Donkey.getInstance().getConfiguration().getDonkeyProperties().get("database"); Long maxId = null;/*from w w w . j av a2 s . c o m*/ if (database.equals("derby") || database.equals("mysql") || database.equals("sqlserver")) { Statement statement = null; ResultSet result = null; try { connection = getConnection(); statement = connection.createStatement(); result = statement.executeQuery("SELECT MAX(id) FROM d_m" + localChannelId); result.next(); maxId = result.getLong(1) + 1; close(result); statement.execute("DELETE FROM d_message_sequences WHERE local_channel_id = " + localChannelId); statement.execute( "INSERT INTO d_message_sequences (local_channel_id) VALUES (" + localChannelId + ")"); connection.commit(); } finally { close(result); close(statement); close(connection); } } logger.debug("Message ID sequence updated to: " + maxId); }