List of usage examples for java.sql Connection commit
void commit() throws SQLException;
Connection
object. From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); conn.setAutoCommit(false);//from w w w. j a v a 2 s .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(); // execute the batch int[] updateCounts = pstmt.executeBatch(); checkUpdateCounts(updateCounts); // 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:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); conn.setAutoCommit(false);/* w ww .ja va2 s .c o m*/ Statement st = conn.createStatement(); st.executeUpdate("create table survey (id int, name VARCHAR(30) );"); st.addBatch("DELETE FROM survey"); st.addBatch("INSERT INTO survey(id, name) " + "VALUES(444, 'ginger')"); // we intentionally pass a table name (animals_tableZZ) // that does not exist st.addBatch("INSERT INTO survey(id, name) " + "VALUES(555, 'lola')"); st.addBatch("INSERT INTO survey(id, name) " + "VALUES(666, 'freddy')"); // Execute the batch int[] updateCounts = st.executeBatch(); checkUpdateCounts(updateCounts); // 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:DemoPreparedStatementSetClob.java
public static void main(String[] args) throws Exception { String id = "0001"; String newID = "0002"; ResultSet rs = null;//from w w w. j a v a 2 s. co m Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); // begin transaction conn.setAutoCommit(false); String query1 = "select clob_column from clob_table where id = ?"; pstmt = conn.prepareStatement(query1); pstmt.setString(1, id); rs = pstmt.executeQuery(); rs.next(); java.sql.Clob clob = (java.sql.Clob) rs.getObject(1); String query = "insert into clob_table(id, clob_column) values(?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, newID); pstmt.setClob(2, clob); int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); conn.commit(); } finally { rs.close(); pstmt.close(); conn.close(); } }
From source file:Main.java
public static void main(String[] args) { Connection conn = null; Statement stmt = null;/* ww w . j a v a2s . co m*/ boolean executeResult; try { String driver = "oracle.jdbc.driver.OracleDriver"; Class.forName(driver).newInstance(); System.out.println("Connecting to database..."); String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL"; conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd"); stmt = conn.createStatement(); conn.setAutoCommit(false); if (!conn.getAutoCommit()) System.out.println("Auto-commit is set to false"); String sql = "INSERT INTO Location VALUES(715,'Houston')"; stmt.executeUpdate(sql); sql = "INSERT INTO Employees VALUES" + "(8,'K','4351',{d '2000-02-00'},715)"; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException se) { String msg = se.getMessage(); msg = "SQLException occured with message: " + msg; System.out.println(msg); System.out.println("Starting rollback operations..."); try { conn.rollback(); } catch (SQLException se2) { se2.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { String url = "jdbc:mysql://localhost/testdb"; String username = "root"; String password = ""; Class.forName("com.mysql.jdbc.Driver"); Connection conn = null; try {/* w w w .j a va 2 s . c om*/ conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); Statement st = conn.createStatement(); st.execute("INSERT INTO orders (username, order_date) VALUES ('java', '2007-12-13')", Statement.RETURN_GENERATED_KEYS); ResultSet keys = st.getGeneratedKeys(); int id = 1; while (keys.next()) { id = keys.getInt(1); } PreparedStatement pst = conn.prepareStatement( "INSERT INTO order_details (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)"); pst.setInt(1, id); pst.setString(2, "1"); pst.setInt(3, 10); pst.setDouble(4, 100); pst.execute(); conn.commit(); System.out.println("Transaction commit..."); } catch (SQLException e) { if (conn != null) { conn.rollback(); System.out.println("Connection rollback..."); } e.printStackTrace(); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } }
From source file:DemoPreparedStatementSetClob.java
public static void main(String[] args) throws Exception { String id = "0001"; String newID = "0002"; ResultSet rs = null;// ww w .ja v a 2s.c o m Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); // begin transaction conn.setAutoCommit(false); String query1 = "select clob_column from clob_table where id = ?"; pstmt = conn.prepareStatement(query1); pstmt.setString(1, id); rs = pstmt.executeQuery(); rs.next(); java.sql.Clob clob = (java.sql.Clob) rs.getObject(1); String query = "insert into clob_table(id, clob_column) values(?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, newID); pstmt.setClob(2, clob); // execute query, and return number of rows created int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); // end transaction conn.commit(); } finally { rs.close(); pstmt.close(); conn.close(); } }
From source file:Main.java
public static void main(String[] args) { long begTime = System.currentTimeMillis(); String driver = DEFAULT_DRIVER; String url = DEFAULT_URL; String username = DEFAULT_USERNAME; String password = DEFAULT_PASSWORD; Connection connection = null; try {//from w ww. j av a2s . c o m connection = createConnection(driver, url, username, password); DatabaseMetaData meta = connection.getMetaData(); System.out.println(meta.getDatabaseProductName()); System.out.println(meta.getDatabaseProductVersion()); String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON"; System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST)); connection.setAutoCommit(false); String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)"; List parameters = Arrays.asList("Foo", "Bar"); int numRowsUpdated = update(connection, sqlUpdate, parameters); connection.commit(); System.out.println("# rows inserted: " + numRowsUpdated); System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST)); } catch (Exception e) { rollback(connection); e.printStackTrace(); } finally { close(connection); long endTime = System.currentTimeMillis(); System.out.println("wall time: " + (endTime - begTime) + " ms"); } }
From source file:DemoPreparedStatementSetBlob.java
public static void main(String[] args) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null;//from w w w . jav a 2 s . c om java.sql.Blob blob = null; try { conn = getConnection(); // prepare blob object from an existing binary column pstmt = conn.prepareStatement("select photo from my_pictures where id = ?"); pstmt.setString(1, "0001"); rs = pstmt.executeQuery(); rs.next(); blob = rs.getBlob(1); // prepare SQL query for inserting a new row using setBlob() String query = "insert into blob_table(id, blob_column) values(?, ?)"; // begin transaction conn.setAutoCommit(false); pstmt = conn.prepareStatement(query); pstmt.setString(1, "0002"); pstmt.setBlob(2, blob); int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); // end transaction conn.commit(); } finally { rs.close(); pstmt.close(); conn.close(); } }
From source file:SimpleProgramToAccessOracleDatabase.java
public static void main(String[] args) throws SQLException { Connection conn = null; // connection object Statement stmt = null; // statement object ResultSet rs = null; // result set object try {/*from w ww . j a va2s. com*/ conn = getConnection(); // without Connection, can not do much // create a statement: This object will be used for executing // a static SQL statement and returning the results it produces. stmt = conn.createStatement(); // start a transaction conn.setAutoCommit(false); // create a table called cats_tricks stmt.executeUpdate("CREATE TABLE cats_tricks " + "(name VARCHAR2(30), trick VARCHAR2(30))"); // insert two new records to the cats_tricks table stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'r')"); stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'j')"); // commit the transaction conn.commit(); // set auto commit to true (from now on every single // statement will be treated as a single transaction conn.setAutoCommit(true); // get all of the the records from the cats_tricks table rs = stmt.executeQuery("SELECT name, trick FROM cats_tricks"); // iterate the result set and get one row at a time while (rs.next()) { String name = rs.getString(1); // 1st column in query String trick = rs.getString(2); // 2nd column in query System.out.println("name=" + name); System.out.println("trick=" + trick); System.out.println("=========="); } } catch (ClassNotFoundException ce) { // if the driver class not found, then we will be here System.out.println(ce.getMessage()); } catch (SQLException e) { // something went wrong, we are handling the exception here if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } System.out.println("--- SQLException caught ---"); // iterate and get all of the errors as much as possible. while (e != null) { System.out.println("Message : " + e.getMessage()); System.out.println("SQLState : " + e.getSQLState()); System.out.println("ErrorCode : " + e.getErrorCode()); System.out.println("---"); e = e.getNextException(); } } finally { // close db resources try { rs.close(); stmt.close(); conn.close(); } catch (Exception e) { } } }
From source file:BatchUpdate.java
public static void main(String args[]) throws SQLException { ResultSet rs = null;/*w ww. j ava2 s . c o m*/ PreparedStatement ps = null; String url = "jdbc:mySubprotocol:myDataSource"; Connection con; Statement stmt; 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"); con.setAutoCommit(false); stmt = con.createStatement(); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)"); int[] updateCounts = stmt.executeBatch(); con.commit(); con.setAutoCommit(true); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("-----BatchUpdateException-----"); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } System.err.println(""); } catch (SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }