List of usage examples for java.sql Connection commit
void commit() throws SQLException;
Connection
object. From source file:UpdateLogic.java
public static void main(String args[]) { Connection con = null; if (args.length != 2) { System.out.println("Syntax: <java UpdateLogic [number] [string]>"); return;/*from www . ja v a 2 s . c o m*/ } try { String driver = "com.imaginary.sql.msql.MsqlDriver"; Class.forName(driver).newInstance(); String url = "jdbc:msql://carthage.imaginary.com/ora"; Statement s; con = DriverManager.getConnection(url, "borg", ""); con.setAutoCommit(false); // make sure auto commit is off! s = con.createStatement();// create the first statement s.executeUpdate("INSERT INTO test (test_id, test_val) " + "VALUES(" + args[0] + ", '" + args[1] + "')"); s.close(); // close the first statement s = con.createStatement(); // create the second statement s.executeUpdate("INSERT into test_desc (test_id, test_desc) " + "VALUES(" + args[0] + ", 'This describes the test.')"); con.commit(); // commit the two statements System.out.println("Insert succeeded."); s.close(); // close the second statement } catch (Exception e) { if (con != null) { try { con.rollback(); } // rollback on error catch (SQLException e2) { } } e.printStackTrace(); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
From source file:DemoPreparedStatementSetBinaryStream.java
public static void main(String[] args) throws Exception { String smallFileName = "smallFileName.dat"; String largeFileName = "largeFileName.dat"; Connection conn = null; PreparedStatement pstmt = null; try {//from w ww . j a v a 2 s .c o m conn = getConnection(); File smallFile = new File(smallFileName); int smallFileLength = (int) smallFile.length(); InputStream smallStream = (InputStream) new FileInputStream(smallFile); File largeFile = new File(largeFileName); int largeFileLength = (int) largeFile.length(); InputStream largeStream = (InputStream) new FileInputStream(largeFile); String query = "insert into binary_table(id, raw_column, long_raw_column) values(?, ?, ?)"; conn.setAutoCommit(false); pstmt = conn.prepareStatement(query); pstmt.setString(1, "0001"); pstmt.setBinaryStream(2, smallStream, smallFileLength); pstmt.setBinaryStream(3, largeStream, largeFileLength); // execute query, and return number of rows created int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); conn.commit(); } finally { pstmt.close(); conn.close(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); conn.setAutoCommit(false);//from w w w. j ava 2s . c o m Statement st = conn.createStatement(); st.executeUpdate("create table survey (id int, name VARCHAR(30) );"); String INSERT_RECORD = "insert into survey(id, name) values(?,?)"; PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD); pstmt.setString(1, "1"); pstmt.setString(2, "name1"); pstmt.addBatch(); pstmt.setString(1, "2"); pstmt.setString(2, "name2"); pstmt.addBatch(); try { // execute the batch int[] updateCounts = pstmt.executeBatch(); } catch (BatchUpdateException e) { int[] updateCounts = e.getUpdateCounts(); checkUpdateCounts(updateCounts); try { conn.rollback(); } catch (Exception e2) { e.printStackTrace(); System.exit(1); } } // since there were no errors, commit conn.commit(); ResultSet rs = st.executeQuery("SELECT * FROM survey"); outputResultSet(rs); rs.close(); st.close(); conn.close(); }
From source file:DemoPreparedStatementSetCharacterStream.java
public static void main(String[] args) throws Exception { String fileName = "charDataFile.txt"; Reader fileReader = null;/*from w w w. java 2 s . c om*/ long fileLength = 0; Connection conn = null; PreparedStatement pstmt = null; try { File file = new File(fileName); fileLength = file.length(); fileReader = (Reader) new BufferedReader(new FileReader(file)); System.out.println("fileName=" + fileName); System.out.println("fileLength=" + fileLength); conn = getConnection(); // begin transaction conn.setAutoCommit(false); // prepare SQL query for inserting a new row using SetCharacterStream() String query = "insert into char_stream_table (id, char_stream_column) values(?, ?)"; // create PrepareStatement object pstmt = conn.prepareStatement(query); pstmt.setString(1, fileName); pstmt.setCharacterStream(2, fileReader, (int) fileLength); // execute query, and return number of rows created int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); // end transaction conn.commit(); } finally { pstmt.close(); conn.close(); } }
From source file:Main.java
public static void main(String[] argv) throws Exception { Class.forName(DB_DRIVER);//from www .java 2s .c o m Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); PreparedStatement preparedStatementInsert = null; PreparedStatement preparedStatementUpdate = null; String insertTableSQL = "INSERT INTO Person" + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES" + "(?,?,?,?)"; String updateTableSQL = "UPDATE Person SET USERNAME =? " + "WHERE USER_ID = ?"; java.util.Date today = new java.util.Date(); dbConnection.setAutoCommit(false); preparedStatementInsert = dbConnection.prepareStatement(insertTableSQL); preparedStatementInsert.setInt(1, 9); preparedStatementInsert.setString(2, "101"); preparedStatementInsert.setString(3, "system"); preparedStatementInsert.setTimestamp(4, new java.sql.Timestamp(today.getTime())); preparedStatementInsert.executeUpdate(); preparedStatementUpdate = dbConnection.prepareStatement(updateTableSQL); preparedStatementUpdate.setString(1, "new string"); preparedStatementUpdate.setInt(2, 999); preparedStatementUpdate.executeUpdate(); dbConnection.commit(); dbConnection.close(); }
From source file:Main.java
public static void main(String[] argv) throws Exception { Connection dbConnection = null; PreparedStatement preparedStatement = null; Class.forName(DB_DRIVER);// w w w. ja v a 2s. c o m dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); String insertTableSQL = "INSERT INTO Person" + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES" + "(?,?,?,?)"; preparedStatement = dbConnection.prepareStatement(insertTableSQL); dbConnection.setAutoCommit(false); java.util.Date today = new java.util.Date(); preparedStatement.setInt(1, 101); preparedStatement.setString(2, "101"); preparedStatement.setString(3, "system"); preparedStatement.setTimestamp(4, new java.sql.Timestamp(today.getTime())); preparedStatement.addBatch(); preparedStatement.setInt(1, 102); preparedStatement.setString(2, "102"); preparedStatement.setString(3, "system"); preparedStatement.setTimestamp(4, new java.sql.Timestamp(today.getTime())); preparedStatement.addBatch(); preparedStatement.setInt(1, 103); preparedStatement.setString(2, "103"); preparedStatement.setString(3, "system"); preparedStatement.setTimestamp(4, new java.sql.Timestamp(today.getTime())); preparedStatement.addBatch(); preparedStatement.executeBatch(); dbConnection.commit(); preparedStatement.close(); dbConnection.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { String WRITE_OBJECT_SQL = "BEGIN " + " INSERT INTO java_objects(object_id, object_name, object_value) " + " VALUES (?, ?, empty_blob()) " + " RETURN object_value INTO ?; " + "END;"; String READ_OBJECT_SQL = "SELECT object_value FROM java_objects WHERE object_id = ?"; Connection conn = getOracleConnection(); conn.setAutoCommit(false);// w w w . j a v a 2s .c o m List<Object> list = new ArrayList<Object>(); list.add("This is a short string."); list.add(new Integer(1234)); list.add(new java.util.Date()); // write object to Oracle long id = 0001; String className = list.getClass().getName(); CallableStatement cstmt = conn.prepareCall(WRITE_OBJECT_SQL); cstmt.setLong(1, id); cstmt.setString(2, className); cstmt.registerOutParameter(3, java.sql.Types.BLOB); cstmt.executeUpdate(); BLOB blob = (BLOB) cstmt.getBlob(3); OutputStream os = blob.getBinaryOutputStream(); ObjectOutputStream oop = new ObjectOutputStream(os); oop.writeObject(list); oop.flush(); oop.close(); os.close(); // Read object from oracle PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL); pstmt.setLong(1, id); ResultSet rs = pstmt.executeQuery(); rs.next(); InputStream is = rs.getBlob(1).getBinaryStream(); ObjectInputStream oip = new ObjectInputStream(is); Object object = oip.readObject(); className = object.getClass().getName(); oip.close(); is.close(); rs.close(); pstmt.close(); conn.commit(); // de-serialize list a java object from a given objectID List listFromDatabase = (List) object; System.out.println("[After De-Serialization] list=" + listFromDatabase); conn.close(); }
From source file:CreateRef.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; Statement stmt;/* w w w . ja v a2 s. com*/ try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { String createManagers = "CREATE TABLE MANAGERS OF MANAGER " + "(OID REF(MANAGER) VALUES ARE SYSTEM GENERATED)"; String insertManager1 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES " + "(000001, 'MONTOYA', 'ALFREDO', '8317225600')"; String insertManager2 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES " + "(000002, 'HASKINS', 'MARGARET', '4084355600')"; String insertManager3 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES " + "(000003, 'CHEN', 'HELEN', '4153785600')"; con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); stmt.executeUpdate(createManagers); con.setAutoCommit(false); stmt.addBatch(insertManager1); stmt.addBatch(insertManager2); stmt.addBatch(insertManager3); int[] updateCounts = stmt.executeBatch(); con.commit(); System.out.println("Update count for: "); for (int i = 0; i < updateCounts.length; i++) { System.out.print(" command " + (i + 1) + " = "); System.out.println(updateCounts[i]); } stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("-----BatchUpdateException-----"); System.err.println("Message: " + b.getMessage()); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts for successful commands: "); int[] rowsUpdated = b.getUpdateCounts(); for (int i = 0; i < rowsUpdated.length; i++) { System.err.print(rowsUpdated[i] + " "); } System.err.println(""); } catch (SQLException ex) { System.err.println("------SQLException------"); System.err.println("Error message: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:MainClass.java
public static void main(String[] args) { Connection connection = null; Statement statement = null;//from ww w .j a v a 2s. co m try { Class.forName("org.hsqldb.jdbcDriver").newInstance(); String url = "jdbc:hsqldb:hsqldb\\demoDatabase"; connection = DriverManager.getConnection(url, "username", "password"); connection.setAutoCommit(false); statement = connection.createStatement(); String update1 = "UPDATE employees SET email = 'a@b.com' WHERE email = 'a@a.com'"; statement.executeUpdate(update1); Savepoint savepoint1 = connection.setSavepoint("savepoint1"); String update2 = "UPDATE employees SET email = 'b@b.com' WHERE email = 'b@c.com'"; statement.executeUpdate(update2); Savepoint savepoint2 = connection.setSavepoint("savepoint2"); String update3 = "UPDATE employees SET email = 'c@c.com' WHERE email = 'c@d.com'"; statement.executeUpdate(update3); Savepoint savepoint3 = connection.setSavepoint("savepoint3"); String update4 = "UPDATE employees SET email = 'd@d.com' WHERE email = 'd@e.com'"; statement.executeUpdate(update4); Savepoint savepoint4 = connection.setSavepoint("savepoint4"); String update5 = "UPDATE employees SET email = 'e@e.com' WHERE email = 'e@f.com'"; statement.executeUpdate(update5); Savepoint savepoint5 = connection.setSavepoint("savepoint5"); connection.rollback(savepoint3); connection.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { } // nothing we can do } if (connection != null) { try { connection.close(); } catch (SQLException e) { } // nothing we can do } } }
From source file:TransactionPairs.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con = null; Statement stmt;//from w w w. j av a 2 s . c o m PreparedStatement updateSales; PreparedStatement updateTotal; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME = ?"; String updateStatement = "update COFFEES " + "set TOTAL = TOTAL + ? where COF_NAME = ?"; 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()); } } } }