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:ImageStringToBlob.java

public static void main(String[] args) {
    Connection conn = null;

    if (args.length != 1) {
        System.out.println("Missing argument: full path to <oscar.properties>");
        return;//  w  w w  .  j ava 2 s. co m
    }

    try {

        FileInputStream fin = new FileInputStream(args[0]);
        Properties prop = new Properties();
        prop.load(fin);

        String driver = prop.getProperty("db_driver");
        String uri = prop.getProperty("db_uri");
        String db = prop.getProperty("db_name");
        String username = prop.getProperty("db_username");
        String password = prop.getProperty("db_password");

        Class.forName(driver);
        conn = DriverManager.getConnection(uri + db, username, password);
        conn.setAutoCommit(true); // no transactions

        /*
         * select all records ids with image_data not null and contents is null
         * for each id fetch record
         * migrate data from image_data to contents
         */
        String sql = "select image_id from client_image where image_data is not null and contents is null";
        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        List<Long> ids = new ArrayList<Long>();

        while (rs.next()) {
            ids.add(rs.getLong("image_id"));
        }

        rs.close();

        sql = "select image_data from client_image where image_id = ?";
        pst = conn.prepareStatement(sql);

        System.out.println("Migrating image data for " + ids.size() + " images...");
        for (Long id : ids) {
            pst.setLong(1, id);
            ResultSet imagesRS = pst.executeQuery();
            while (imagesRS.next()) {
                String dataString = imagesRS.getString("image_data");
                Blob dataBlob = fromStringToBlob(dataString);
                if (writeBlobToDb(conn, id, dataBlob) == 1) {
                    System.out.println("Image data migrated for image_id: " + id);
                }
            }
            imagesRS.close();
        }
        System.out.println("Migration completed.");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

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 a  v a 2s. co  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());
            }
        }
    }
}

From source file:TransactionPairs.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con = null;
    Statement stmt;/*from  www. j  a  v a2  s.c  o 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:CreateRef.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;
    Statement stmt;/*from   w w  w.  jav  a2  s  . c  o  m*/
    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:je3.rmi.MudClient.java

/**
 * This main() method is the standalone program that figures out what
 * database to connect to with what driver, connects to the database,
 * creates a PersistentBankServer object, and registers it with the registry,
 * making it available for client use/* w w  w.  jav a  2 s.c  o  m*/
 **/
public static void main(String[] args) {
    try {
        // Create a new Properties object.  Attempt to initialize it from
        // the BankDB.props file or the file optionally specified on the 
        // command line, ignoring errors.
        Properties p = new Properties();
        try { p.load(new FileInputStream(args[0])); }
        catch (Exception e) {
            try { p.load(new FileInputStream("BankDB.props")); }
            catch (Exception e2) {}
        }
       
        // The BankDB.props file (or file specified on the command line)
        // must contain properties "driver" and "database", and may
        // optionally contain properties "user" and "password".
        String driver = p.getProperty("driver");
        String database = p.getProperty("database");
        String user = p.getProperty("user", "");
        String password = p.getProperty("password", "");
       
        // Load the database driver class
        Class.forName(driver);
       
        // Connect to the database that stores our accounts
        Connection db = DriverManager.getConnection(database,
                 user, password);
       
        // Configure the database to allow multiple queries and updates
        // to be grouped into atomic transactions
        db.setAutoCommit(false);
        db.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
       
        // Create a server object that uses our database connection
        PersistentBankServer bank = new PersistentBankServer(db);
       
        // Read a system property to figure out how to name this server.
        // Use "SecondRemote" as the default.
        String name = System.getProperty("bankname", "SecondRemote");
       
        // Register the server with the name
        Naming.rebind(name, bank);
       
        // And tell everyone that we're up and running.
        System.out.println(name + " is open and ready for customers.");
    }
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException) 
            System.err.println("SQL State: " +
           ((SQLException)e).getSQLState());
        System.err.println("Usage: java [-Dbankname=<name>] " +
          "je3.rmi.PersistentBankServer " +
            "[<dbpropsfile>]");
        System.exit(1);
    }
}

From source file:$.DeviceTypeDAO.java

public static void beginTransaction() throws DeviceMgtPluginException {
        try {//from w w w  .j  a va 2s  .c  o  m
            Connection conn = dataSource.getConnection();
            conn.setAutoCommit(false);
            currentConnection.set(conn);
        } catch (SQLException e) {
            throw new DeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
        }
    }

From source file:com.espertech.esperio.db.SupportDatabaseService.java

public static void truncateTable(String tableName) throws SQLException {
    Connection connection = getConnection(PARTURL, DBUSER, DBPWD);
    connection.setAutoCommit(true);
    Statement stmt = connection.createStatement();
    String sql = "delete from " + tableName;
    log.info("Executing sql : " + sql);
    stmt.executeUpdate(sql);/*from  w w w  . j  a  v a  2s.  co  m*/
    stmt.close();
    connection.close();
}

From source file:com.espertech.esperio.db.SupportDatabaseService.java

public static Object[][] readAll(String tableName) throws SQLException {
    Connection connection = getConnection(PARTURL, DBUSER, DBPWD);
    connection.setAutoCommit(true);
    Statement stmt = connection.createStatement();
    String sql = "select * from " + tableName;
    log.info("Executing sql : " + sql);
    ResultSet resultSet = stmt.executeQuery(sql);

    List<Object[]> rows = new ArrayList<Object[]>();
    while (resultSet.next()) {
        List<Object> row = new ArrayList<Object>();
        for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
            row.add(resultSet.getObject(i + 1));
        }//from w ww. j av  a 2s  .  c o m
        rows.add(row.toArray());
    }

    Object[][] arr = new Object[rows.size()][];
    for (int i = 0; i < rows.size(); i++) {
        arr[i] = rows.get(i);
    }

    stmt.close();
    connection.close();
    return arr;
}

From source file:com.chiralbehaviors.CoRE.kernel.KernelUtil.java

public static void clear(EntityManager em) throws SQLException {
    Connection connection = em.unwrap(Connection.class);
    connection.setAutoCommit(false);
    alterTriggers(connection, false);/*ww  w  .j a  v a2 s  .  c o  m*/
    ResultSet r = connection.createStatement().executeQuery(KernelUtil.SELECT_TABLE);
    while (r.next()) {
        String table = r.getString("name");
        String query = String.format("DELETE FROM %s", table);
        connection.createStatement().execute(query);
    }
    r.close();
    alterTriggers(connection, true);
    CACHED_KERNEL.set(null);
    connection.commit();
}

From source file:com.kaidad.utilities.MBTilesBase64Converter.java

private static Connection connectToDb(String dbName) {
    Connection c = null;
    try {//from w ww .ja v  a2 s .com
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:" + dbName);
        c.setAutoCommit(false);
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }
    System.out.println("Opened database [" + dbName + "] successfully");
    return c;
}