Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

In this page you can find the example usage for java.sql Connection setAutoCommit.

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:SetSavepoint.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    try {/*from  www.jav  a  2  s.c o 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:Main.java

public static void main(String[] args) throws Exception {
    Connection connection = null;
    try {/*from   w  ww  . ja v  a 2s  .c  o  m*/
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        connection = DriverManager.getConnection("jdbc:sqlserver://MYSERVER;databaseName=MYDATABASE", "USERID",
                "PASSWORD");

        connection.setAutoCommit(false);

        Statement statement = connection.createStatement();

        statement.executeUpdate("UPDATE Table1 SET Value = 1 WHERE Name = 'foo'");
        statement.executeUpdate("UPDATE Table2 SET Value = 2 WHERE Name = 'bar'");

        connection.commit();

    } catch (SQLException ex) {
        connection.rollback();
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    Connection con;
    Statement stmt;/*from  w  ww .jav a 2 s  .c o m*/
    ResultSet rs;

    try {
        Class.forName(driver);
        con = DriverManager.getConnection("jdbc:odbc:databaseName", "student", "student");
        // Start a transaction
        con.setAutoCommit(false);

        stmt = con.createStatement();
        stmt.addBatch("UPDATE EMP SET JOB = 1");

        // Submit the batch of commands for this statement to the database
        stmt.executeBatch();

        // Commit the transaction
        con.commit();

        // Close the existing to be safe before opening a new one
        stmt.close();

        // Print out the Employees
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * FROM EMP");
        // Loop through and print the employee number, job, and hiredate
        while (rs.next()) {
            int id = rs.getInt("EMPNO");
            int job = rs.getInt("JOB");
            String hireDate = rs.getString("HIREDATE");

            System.out.println(id + ":" + job + ":" + hireDate);
        }
        con.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

From source file:InsertPictureToMySql.java

public static void main(String[] args) throws Exception, IOException, SQLException {
    Class.forName("org.gjt.mm.mysql.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
    String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";

    FileInputStream fis = null;/*from   w ww.ja  v a  2 s . co m*/
    PreparedStatement ps = null;
    try {
        conn.setAutoCommit(false);
        File file = new File("myPhoto.png");
        fis = new FileInputStream(file);
        ps = conn.prepareStatement(INSERT_PICTURE);
        ps.setString(1, "001");
        ps.setString(2, "name");
        ps.setBinaryStream(3, fis, (int) file.length());
        ps.executeUpdate();
        conn.commit();
    } finally {
        ps.close();
        fis.close();
    }
}

From source file:TestBatchUpdate.java

public static void main(String args[]) {
    Connection conn = null;
    Statement stmt = null;/*from   w  ww  . j ava2  s. c o  m*/
    ResultSet rs = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        conn.setAutoCommit(false);
        stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('11', 'A')");
        stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('22', 'B')");
        stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('33', 'C')");
        int[] updateCounts = stmt.executeBatch();
        conn.commit();

        rs = stmt.executeQuery("SELECT * FROM batch_table");
        while (rs.next()) {
            String id = rs.getString("id");
            String name = rs.getString("name");
            System.out.println("id=" + id + "  name=" + name);
        }

    } catch (BatchUpdateException b) {
        System.err.println("SQLException: " + b.getMessage());
        System.err.println("SQLState: " + b.getSQLState());
        System.err.println("Message: " + b.getMessage());
        System.err.println("Vendor error code: " + b.getErrorCode());
        System.err.print("Update counts: ");
        int[] updateCounts = b.getUpdateCounts();
        for (int i = 0; i < updateCounts.length; i++) {
            System.err.print(updateCounts[i] + " ");
        }
    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
        System.err.println("SQLState: " + ex.getSQLState());
        System.err.println("Message: " + ex.getMessage());
        System.err.println("Vendor error code: " + ex.getErrorCode());
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    Connection connection = null;
    Statement statement = null;//from www  . j ava  2 s  .c o 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:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("org.apache.derby.jdbc.ClientDriver");
    Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/testDb", "name", "pass");
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    String insertEmp1 = "insert into emp values(10,'A','trainee')";
    String insertEmp2 = "insert into emp values(11,'B','trainee')";
    String insertEmp3 = "insert into emp values(12,'C','trainee')";
    con.setAutoCommit(false);
    stmt.addBatch(insertEmp1);/*from   w  w  w  . ja  v  a  2  s . co  m*/
    stmt.addBatch(insertEmp2);
    stmt.addBatch(insertEmp3);
    ResultSet rs = stmt.executeQuery("select * from emp");
    rs.last();
    System.out.println("rows before batch execution= " + rs.getRow());
    stmt.executeBatch();
    con.commit();
    System.out.println("Batch executed");
    rs = stmt.executeQuery("select * from emp");
    rs.last();
    System.out.println("rows after batch execution= " + rs.getRow());
}

From source file:DemoPreparedStatementSetCharacterStream.java

public static void main(String[] args) throws Exception {
    String fileName = "charDataFile.txt";
    Reader fileReader = null;/*ww w. j a  va2 s . co  m*/
    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 {
    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;
    Class.forName(DB_DRIVER);//from   w  ww .java 2 s .  com
    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) {
    Connection conn = null;
    Statement stmt = null;/* w ww .j  av  a 2s.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();
    }
}