List of usage examples for java.sql Connection commit
void commit() throws SQLException;
Connection
object. From source file:TransactionPairs.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con = null; Statement stmt;//from w ww .j ava 2 s.co m PreparedStatement updateSales; PreparedStatement updateTotal; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME like ?"; String updateStatement = "update COFFEES " + "set TOTAL = TOTAL + ? where COF_NAME like ?"; String query = "select COF_NAME, SALES, TOTAL from COFFEES"; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); updateSales = con.prepareStatement(updateString); updateTotal = con.prepareStatement(updateStatement); int[] salesForWeek = { 175, 150, 60, 155, 90 }; String[] coffees = { "Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf" }; int len = coffees.length; con.setAutoCommit(false); for (int i = 0; i < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); updateTotal.setInt(1, salesForWeek[i]); updateTotal.setString(2, coffees[i]); updateTotal.executeUpdate(); con.commit(); } con.setAutoCommit(true); updateSales.close(); updateTotal.close(); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String c = rs.getString("COF_NAME"); int s = rs.getInt("SALES"); int t = rs.getInt("TOTAL"); System.out.println(c + " " + s + " " + t); } stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); if (con != null) { try { System.err.print("Transaction is being "); System.err.println("rolled back"); con.rollback(); } catch (SQLException excep) { System.err.print("SQLException: "); System.err.println(excep.getMessage()); } } } }
From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java
public static void main(String[] args) { try {//ww w . ja v a2 s.c o m BasicConfigurator.configure(); //loadProperties(); if (args.length < 2) { System.out.println("Usage: BuildTestbed <testbedID> <inputfile>"); System.exit(0); } int testbedID = Integer.parseInt(args[0]); String filename = args[1]; Connection conn = null; Statement statement = null; MoteSqlAdapter adapter = new MoteSqlAdapter(); Map<Integer, Mote> motes = adapter.readMotes(); log.info(motes); String connStr = System.getProperty("nestbed.options.databaseConnectionString"); log.info("connStr: " + connStr); conn = DriverManager.getConnection(connStr); statement = conn.createStatement(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = in.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); int address = Integer.parseInt(tokenizer.nextToken()); String serial = tokenizer.nextToken(); int xLoc = Integer.parseInt(tokenizer.nextToken()); int yLoc = Integer.parseInt(tokenizer.nextToken()); log.info("Input Mote:\n" + "-----------\n" + "address: " + address + "\n" + "serial: " + serial + "\n" + "xLoc: " + xLoc + "\n" + "yLoc: " + yLoc); for (Mote i : motes.values()) { if (i.getMoteSerialID().equals(serial)) { String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress," + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", " + address + ", " + xLoc + ", " + yLoc + ")"; log.info(query); statement.executeUpdate(query); } } } conn.commit(); } catch (Exception ex) { log.error("Exception in main", ex); } }
From source file:SetSavepoint.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; try {/* www . j ava2 s . co m*/ Class.forName("myDriver.className"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); con.setAutoCommit(false); String query = "SELECT COF_NAME, PRICE FROM COFFEES " + "WHERE TOTAL > ?"; String update = "UPDATE COFFEES SET PRICE = ? " + "WHERE COF_NAME = ?"; PreparedStatement getPrice = con.prepareStatement(query); PreparedStatement updatePrice = con.prepareStatement(update); getPrice.setInt(1, 7000); ResultSet rs = getPrice.executeQuery(); Savepoint save1 = con.setSavepoint(); while (rs.next()) { String cof = rs.getString("COF_NAME"); float oldPrice = rs.getFloat("PRICE"); float newPrice = oldPrice + (oldPrice * .05f); updatePrice.setFloat(1, newPrice); updatePrice.setString(2, cof); updatePrice.executeUpdate(); System.out.println("New price of " + cof + " is " + newPrice); if (newPrice > 11.99) { con.rollback(save1); } } getPrice = con.prepareStatement(query); updatePrice = con.prepareStatement(update); getPrice.setInt(1, 8000); rs = getPrice.executeQuery(); System.out.println(); Savepoint save2 = con.setSavepoint(); while (rs.next()) { String cof = rs.getString("COF_NAME"); float oldPrice = rs.getFloat("PRICE"); float newPrice = oldPrice + (oldPrice * .05f); updatePrice.setFloat(1, newPrice); updatePrice.setString(2, cof); updatePrice.executeUpdate(); System.out.println("New price of " + cof + " is " + newPrice); if (newPrice > 11.99) { con.rollback(save2); } } con.commit(); Statement stmt = con.createStatement(); rs = stmt.executeQuery("SELECT COF_NAME, " + "PRICE FROM COFFEES"); System.out.println(); while (rs.next()) { String name = rs.getString("COF_NAME"); float price = rs.getFloat("PRICE"); System.out.println("Current price of " + name + " is " + price); } con.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:$.DeviceTypeDAO.java
public static void commitTransaction() throws DeviceMgtPluginException { try {//from w ww .j ava 2s . co m Connection conn = currentConnection.get(); if (conn != null) { conn.commit(); } else { if (log.isDebugEnabled()) { log.debug("Datasource connection associated with the current thread is null, hence commit " + "has not been attempted"); } } } catch (SQLException e) { throw new DeviceMgtPluginException("Error occurred while committing the transaction", e); } finally { closeConnection(); } }
From source file:io.kazuki.v0.internal.helper.TestHelper.java
public static void dropSchema(DataSource database) { Connection conn = null; try {//from www . j a v a 2 s. c o m conn = database.getConnection(); conn.prepareStatement("DROP ALL OBJECTS").execute(); conn.commit(); } catch (Exception e) { throw Throwables.propagate(e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { throw Throwables.propagate(e); } } } }
From source file:com.silverpeas.components.model.AbstractJndiCase.java
public static void executeDDL(IDatabaseConnection databaseConnection, String filename) { Connection connection = null; try {/*from w ww . j a v a2 s . c om*/ connection = databaseConnection.getConnection(); Statement st = connection.createStatement(); st.execute(loadDDL(filename)); connection.commit(); } catch (Exception e) { LoggerFactory.getLogger(AbstractJndiCase.class).error("Error creating tables", e); } }
From source file:com.sf.ddao.TxHelper.java
public static <T, SK> T execInTx(TransactionableDao<SK> dao, Callable<T> callable, SK... shardKeys) throws Exception { Context context = dao.startTransaction(shardKeys == null || shardKeys.length == 0 ? null : shardKeys[0]); boolean success = false; Connection conn; try {/* w w w . ja va2 s. c o m*/ conn = ConnectionHandlerHelper.getConnectionOnHold(context); connectionOnHold.set(conn); conn.setAutoCommit(false); T res = callable.call(); conn.commit(); success = true; return res; } finally { connectionOnHold.remove(); conn = ConnectionHandlerHelper.releaseConnectionOnHold(context); if (!success) { conn.rollback(); } conn.close(); } }
From source file:com.adaptris.core.util.JdbcUtil.java
/** * Commit any pending transactions on the Connection. * <p>/* www. j a v a2 s .c o m*/ * If {@link Connection#getAutoCommit()} is true, then this operation does nothing. * </p> * * @param sqlConnection the SQL Connection * @throws SQLException if the commit fails. */ public static void commit(Connection sqlConnection) throws SQLException { if (sqlConnection == null) { return; } if (!sqlConnection.getAutoCommit()) { sqlConnection.commit(); } }
From source file:com.splicemachine.derby.test.framework.SpliceFunctionWatcher.java
public static void executeDrop(String schemaName, String functionName) { LOG.trace("executeDrop"); Connection connection = null; Statement statement = null;/* www . j ava 2s . com*/ try { connection = SpliceNetConnection.getConnection(); statement = connection.createStatement(); statement.execute("drop function " + schemaName.toUpperCase() + "." + functionName.toUpperCase()); connection.commit(); } catch (Exception e) { LOG.error("error Dropping " + e.getMessage()); e.printStackTrace(); throw new RuntimeException(e); } finally { DbUtils.closeQuietly(statement); DbUtils.commitAndCloseQuietly(connection); } }
From source file:com.hangum.tadpole.engine.manager.TadpoleSQLTransactionManager.java
/** * transaction commit/* w ww. j av a2 s.com*/ * * @param userId * @param userDB */ public static void commit(final String userId, final UserDBDAO userDB) { if (logger.isDebugEnabled()) { logger.debug("============================================================================="); logger.debug("\t commit [userId]" + getKey(userId, userDB)); logger.debug("============================================================================="); } synchronized (dbManager) { TransactionDAO transactionDAO = dbManager.get(getKey(userId, userDB)); if (transactionDAO != null) { Connection conn = transactionDAO.getConn(); try { logger.debug("\tIs auto commit " + conn.getAutoCommit()); conn.commit(); } catch (Exception e) { logger.error("commit exception", e); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { } } removeInstance(userId, userDB); } } // end synchronized }