Example usage for java.sql Connection setTransactionIsolation

List of usage examples for java.sql Connection setTransactionIsolation

Introduction

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

Prototype

void setTransactionIsolation(int level) throws SQLException;

Source Link

Document

Attempts to change the transaction isolation level for this Connection object to the one given.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();

    DatabaseMetaData dbMd = conn.getMetaData();
    if (dbMd.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED)) {
        System.out.println("Transaction Isolation level " + "TRANSACTION_READ_COMMITTED is supported.");
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }/*from   w ww .j  a va2s .  c o  m*/

    conn.close();
}

From source file:TXInfo.java

public static void main(String[] a) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:MusicVideo");
    int tx = con.getMetaData().getDefaultTransactionIsolation();
    String txtxt = null;//from   ww w. ja v a2 s .com
    switch (tx) {
    case Connection.TRANSACTION_NONE:
        txtxt = "TRANSACTION_NONE";
        break;
    case Connection.TRANSACTION_READ_COMMITTED:
        txtxt = "TRANSACTION_READ_COMMITTED";
        break;
    case Connection.TRANSACTION_READ_UNCOMMITTED:
        txtxt = "TRANSACTION_READ_UNCOMMITTED";
        break;
    case Connection.TRANSACTION_REPEATABLE_READ:
        txtxt = "TRANSACTION_REPEATABLE_READ";
        break;
    case Connection.TRANSACTION_SERIALIZABLE:
        txtxt = "TRANSACTION_SERIALIZABLE";
        break;
    default:
        txtxt = "UNKNOWN!!";
    }
    System.out.println(txtxt);
    con.setTransactionIsolation(tx);
    System.out.println("Done");
    con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
    System.out.println("TX is now " + con.getTransactionIsolation());
}

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//from  ww w  . j  av a  2  s  .c om
 **/
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:org.apache.sqoop.connector.jdbc.oracle.util.OracleConnectionFactory.java

public static void initializeOracleConnection(Connection connection, ConnectionConfig config)
        throws SQLException {

    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    connection.setAutoCommit(false);/*from  w w w  .java2  s. co m*/

    OracleQueries.setConnectionTimeZone(connection, config.timeZone);

    setSessionClientInfo(connection, config);

    OracleQueries.setJdbcFetchSize(connection, config.fetchSize);

    executeOraOopSessionInitializationStatements(connection, config.initializationStatements);
}

From source file:org.wso2.carbon.appfactory.core.util.AppFactoryDBUtil.java

public static synchronized Connection getConnection() throws SQLException {
    Connection connection = dataSource.getConnection();
    connection.setAutoCommit(false);//from ww  w .  j  ava  2s  . c o  m
    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return connection;
}

From source file:org.apache.ode.utils.DbIsolation.java

/**
 * Set Ode-specific isolation level on the connection, if needed.
 *//*from w w  w . jav  a  2  s . c  o m*/
public static void setIsolationLevel(Connection c) throws SQLException {
    try {
        if (_isolationLevel != 0 && c.getTransactionIsolation() != _isolationLevel) {
            if (__log.isDebugEnabled())
                __log.debug("Set isolation level to " + _isolationLevel);
            c.setTransactionIsolation(_isolationLevel);
        }
    } catch (Exception e) {
        if (__log.isDebugEnabled())
            __log.debug("Error while setting isolation level to " + _isolationLevel, e);
    }
}

From source file:org.wso2.carbon.identity.agent.outbound.server.util.DatabaseUtil.java

/**
 * Get database connection./*from w  w w . ja va  2  s  .c  om*/
 * @return SQL connection
 * @throws SQLException
 */
public static Connection getDBConnection() throws SQLException {
    Connection dbConnection = getJDBCDataSource().getConnection();
    dbConnection.setAutoCommit(false);
    if (dbConnection.getTransactionIsolation() != java.sql.Connection.TRANSACTION_READ_COMMITTED) {
        dbConnection.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED);
    }
    return dbConnection;
}

From source file:org.wso2.carbon.user.core.util.DatabaseUtil.java

public static Connection getDBConnection(DataSource dataSource) throws SQLException {
    Connection dbConnection = dataSource.getConnection();
    dbConnection.setAutoCommit(false);/* ww  w.jav a2 s  . c o m*/
    if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }
    return dbConnection;
}

From source file:com.krawler.database.DbPool.java

/**
 * return a connection to use for the Krawler database.
 * /*from   w ww  . j  a  v  a2s  .com*/
 * @param
 * @return
 * @throws ServiceException
 */
public static Connection getConnection() throws ServiceException {
    java.sql.Connection conn = null;

    long start = KrawlerPerf.STOPWATCH_DB_CONN.start();

    try {
        conn = sPoolingDataSource.getConnection();

        if (conn.getAutoCommit() != false)
            conn.setAutoCommit(false);

        // We want READ COMMITTED transaction isolation level for duplicate
        // handling code in BucketBlobStore.newBlobInfo().
        conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED);
    } catch (SQLException e) {
        throw ServiceException.FAILURE("getting database connection", e);
    }

    // If the connection pool is overutilized, warn about potential leaks
    int numActive = sConnectionPool.getNumActive();
    int maxActive = sConnectionPool.getMaxActive();

    if (numActive > maxActive * 0.75) {
        String stackTraceMsg = "Turn on debug logging for KrawlerLog.dbconn to see stack "
                + "traces of connections not returned to the pool.";
        if (KrawlerLog.dbconn.isDebugEnabled()) {
            StringBuffer buf = new StringBuffer();
            synchronized (sConnectionStackCounter) {
                Iterator i = sConnectionStackCounter.iterator();
                while (i.hasNext()) {
                    String stackTrace = (String) i.next();
                    int count = sConnectionStackCounter.getCount(stackTrace);
                    if (count == 0) {
                        i.remove();
                    } else {
                        buf.append(count + " connections allocated at " + stackTrace + "\n");
                    }
                }
            }
            stackTraceMsg = buf.toString();
        }
        KrawlerLog.dbconn.warn("Connection pool is 75% utilized.  " + numActive
                + " connections out of a maximum of " + maxActive + " in use.  " + stackTraceMsg);
    }

    if (KrawlerLog.sqltrace.isDebugEnabled() || KrawlerLog.perf.isDebugEnabled()) {
        // conn = new DebugConnection(conn); //TODO: uncomment later[BS]
    }
    Connection krawlerCon = new Connection(conn);

    // If we're debugging, update the counter with the current stack trace
    if (KrawlerLog.dbconn.isDebugEnabled()) {
        Throwable t = new Throwable();
        krawlerCon.setStackTrace(t);

        String stackTrace = SystemUtil.getStackTrace(t);
        synchronized (sConnectionStackCounter) {
            sConnectionStackCounter.increment(stackTrace);
        }
    }

    KrawlerPerf.STOPWATCH_DB_CONN.stop(start);
    return krawlerCon;
}

From source file:org.cfr.capsicum.datasource.DataSourceUtils.java

/**
 * Reset the given Connection after a transaction,
 * regarding read-only flag and isolation level.
 * @param con the Connection to reset/*w ww .  j  a  v  a  2 s .  c o m*/
 * @param previousIsolationLevel the isolation level to restore, if any
 * @see #prepareConnectionForTransaction
 */
public static void resetConnectionAfterTransaction(Connection con, Integer previousIsolationLevel) {
    Assert.notNull(con, "No Connection specified");
    try {
        // Reset transaction isolation to previous value, if changed for the transaction.
        if (previousIsolationLevel != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Resetting isolation level of JDBC Connection [" + con + "] to "
                        + previousIsolationLevel);
            }
            con.setTransactionIsolation(previousIsolationLevel.intValue());
        }

        // Reset read-only flag.
        if (con.isReadOnly()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]");
            }
            con.setReadOnly(false);
        }
    } catch (Throwable ex) {
        logger.debug("Could not reset JDBC Connection after transaction", ex);
    }
}