Java Code Examples for java.sql.Connection.setTransactionIsolation()

The following are Jave code examples for showing how to use setTransactionIsolation() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dev-courses   File: TestStoredProcedure.java   View Source Code Vote up 6 votes
public static void procWithResultTwo(Connection conn, Integer[] intparam,
                                     ResultSet[] resultparamOne,
                                     ResultSet[] resultparamTwo)
                                     throws SQLException {

    conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(
        "select count(*) from information_schema.columns where table_name='LOB_IDS' and table_schema='SYSTEM_LOBS'");

    if (rs.next()) {
        intparam[0] = rs.getInt(1);

        rs.close();
    }

    resultparamOne[0] = st.executeQuery(
        "select table_schema, table_name from information_schema.tables where table_name='LOB_IDS' and table_schema='SYSTEM_LOBS'");
    resultparamTwo[0] = st.executeQuery(
        "select table_schema, table_name from information_schema.tables where table_name='LOBS' and table_schema='SYSTEM_LOBS'");
}
 
Example 2
Project: parabuild-ci   File: RCData.java   View Source Code Vote up 6 votes
static public void setTI(Connection c, String tiString)
        throws SQLException {
    int i = -1;
    if (tiString.equals("TRANSACTION_READ_UNCOMMITTED"))
        i = Connection.TRANSACTION_READ_UNCOMMITTED;
    if (tiString.equals("TRANSACTION_READ_COMMITTED"))
        i = Connection.TRANSACTION_READ_COMMITTED;
    if (tiString.equals("TRANSACTION_REPEATABLE_READ"))
        i = Connection.TRANSACTION_REPEATABLE_READ;
    if (tiString.equals("TRANSACTION_SERIALIZABLE"))
        i = Connection.TRANSACTION_SERIALIZABLE;
    if (tiString.equals("TRANSACTION_NONE"))
        i = Connection.TRANSACTION_NONE;
    if (i < 0) {
        throw new SQLException(
                "Trans. isol. value not supported by "
                + RCData.class.getName() + ": " + tiString);
    }
    c.setTransactionIsolation(i);
}
 
Example 3
Project: s-store   File: RCData.java   View Source Code Vote up 6 votes
static public void setTI(Connection c, String tiString)
        throws SQLException {
    int i = -1;
    if (tiString.equals("TRANSACTION_READ_UNCOMMITTED"))
        i = Connection.TRANSACTION_READ_UNCOMMITTED;
    if (tiString.equals("TRANSACTION_READ_COMMITTED"))
        i = Connection.TRANSACTION_READ_COMMITTED;
    if (tiString.equals("TRANSACTION_REPEATABLE_READ"))
        i = Connection.TRANSACTION_REPEATABLE_READ;
    if (tiString.equals("TRANSACTION_SERIALIZABLE"))
        i = Connection.TRANSACTION_SERIALIZABLE;
    if (tiString.equals("TRANSACTION_NONE"))
        i = Connection.TRANSACTION_NONE;
    if (i < 0) {
        throw new SQLException(
                "Trans. isol. value not supported by "
                + RCData.class.getName() + ": " + tiString);
    }
    c.setTransactionIsolation(i);
}
 
Example 4
Project: dev-courses   File: RCData.java   View Source Code Vote up 6 votes
/**
 * Set Transaction Isolation level on the specified JDBC Connection
 */
public static void setTI(Connection c, String tiString)
        throws SQLException {
    int i = -1;
    if (tiString.equals("TRANSACTION_READ_UNCOMMITTED"))
        i = Connection.TRANSACTION_READ_UNCOMMITTED;
    if (tiString.equals("TRANSACTION_READ_COMMITTED"))
        i = Connection.TRANSACTION_READ_COMMITTED;
    if (tiString.equals("TRANSACTION_REPEATABLE_READ"))
        i = Connection.TRANSACTION_REPEATABLE_READ;
    if (tiString.equals("TRANSACTION_SERIALIZABLE"))
        i = Connection.TRANSACTION_SERIALIZABLE;
    if (tiString.equals("TRANSACTION_NONE"))
        i = Connection.TRANSACTION_NONE;
    if (i < 0) {
        throw new SQLException(
                "Trans. isol. value not supported by "
                + RCData.class.getName() + ": " + tiString);
    }
    c.setTransactionIsolation(i);
}
 
Example 5
Project: lams   File: DataSourceUtils.java   View Source Code Vote up 6 votes
/**
 * Reset the given Connection after a transaction,
 * regarding read-only flag and isolation level.
 * @param con the Connection to reset
 * @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);
		}

		// 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);
	}
}
 
Example 6
Project: nh-micro   File: MicroXaDataSource.java   View Source Code Vote up 6 votes
private Connection recreateConn(Connection conn) throws SQLException {

    	log.debug("recreating conn xid="+getStr4XidLocal());
    	if(conn!=null){
    		try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
    		conn=null;
    	}
		Connection connection=DriverManager.getConnection(url, username, password); 
		connection.setAutoCommit(false);
		connection.setTransactionIsolation(level);

		return connection;
    }
 
Example 7
Project: agroal   File: ConnectionFactory.java   View Source Code Vote up 5 votes
public Connection createConnection() throws SQLException {
    Connection connection = driver.connect( configuration.jdbcUrl(), jdbcProperties );
    connection.setAutoCommit( configuration.autoCommit() );
    if ( configuration.jdbcTransactionIsolation().isDefined() ) {
        connection.setTransactionIsolation( configuration.jdbcTransactionIsolation().level() );
    }
    if ( configuration.initialSql() != null && !configuration.initialSql().isEmpty() ) {
        try ( Statement statement = connection.createStatement() ) {
            statement.execute( configuration.initialSql() );
        }
    }
    return connection;
}
 
Example 8
Project: ProyectoPacientes   File: StatementRegressionTest.java   View Source Code Vote up 5 votes
private long timeBatch(Connection c, int numberOfRows) throws SQLException {
    this.pstmt = c.prepareStatement("INSERT INTO testBug41532(ID, S1, S2, S3, D1, D2, D3, N1, N2, N3) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
            + " ON DUPLICATE KEY UPDATE S1 = VALUES(S1), S2 = VALUES(S2), S3 = VALUES(S3), D1 = VALUES(D1), D2 ="
            + " VALUES(D2), D3 = VALUES(D3), N1 = N1 + VALUES(N1), N2 = N2 + VALUES(N2), N2 = N2 + VALUES(N2)");
    c.setAutoCommit(false);
    c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    Date d1 = new Date(currentTimeMillis());
    Date d2 = new Date(currentTimeMillis() + 1000000);
    Date d3 = new Date(currentTimeMillis() + 1250000);

    for (int i = 0; i < numberOfRows; i++) {
        this.pstmt.setObject(1, new Integer(i), Types.INTEGER);
        this.pstmt.setObject(2, String.valueOf(i), Types.VARCHAR);
        this.pstmt.setObject(3, String.valueOf(i * 0.1), Types.VARCHAR);
        this.pstmt.setObject(4, String.valueOf(i / 3), Types.VARCHAR);
        this.pstmt.setObject(5, new Timestamp(d1.getTime()), Types.TIMESTAMP);
        this.pstmt.setObject(6, new Timestamp(d2.getTime()), Types.TIMESTAMP);
        this.pstmt.setObject(7, new Timestamp(d3.getTime()), Types.TIMESTAMP);
        this.pstmt.setObject(8, new BigDecimal(i + 0.1), Types.DECIMAL);
        this.pstmt.setObject(9, new BigDecimal(i * 0.1), Types.DECIMAL);
        this.pstmt.setObject(10, new BigDecimal(i / 3), Types.DECIMAL);
        this.pstmt.addBatch();
    }
    long startTime = currentTimeMillis();
    this.pstmt.executeBatch();
    c.commit();
    long stopTime = currentTimeMillis();

    this.rs = this.conn.createStatement().executeQuery("SELECT COUNT(*) FROM testBug41532");
    assertTrue(this.rs.next());
    assertEquals(numberOfRows, this.rs.getInt(1));

    return stopTime - startTime;
}
 
Example 9
Project: sstore-soft   File: ConnectionDefaults.java   View Source Code Vote up 5 votes
public void setDefaults(Connection connection) throws SQLException {

        connection.setHoldability(this.holdability);

        if (this.transactionIsolation != Connection.TRANSACTION_NONE) {
            connection.setTransactionIsolation(this.transactionIsolation);
        }
        connection.setAutoCommit(this.isAutoCommit);
        connection.setReadOnly(this.isReadOnly);
        connection.setCatalog(this.catalog);
    }
 
Example 10
Project: ats-framework   File: SQLServerDbReadAccess.java   View Source Code Vote up 5 votes
protected Connection getConnection() throws DatabaseAccessException {

        Connection connection = super.getConnection();
        try {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } catch (SQLException e) {
            // Not a big deal, we will not read the entities which are in the process
            // of being inserted, but the transaction is still not completed
        }
        return connection;
    }
 
Example 11
Project: s-store   File: ConnectionDefaults.java   View Source Code Vote up 5 votes
public void setDefaults(Connection connection) throws SQLException {

        connection.setHoldability(this.holdability);

        if (this.transactionIsolation != Connection.TRANSACTION_NONE) {
            connection.setTransactionIsolation(this.transactionIsolation);
        }
        connection.setAutoCommit(this.isAutoCommit);
        connection.setReadOnly(this.isReadOnly);
        connection.setCatalog(this.catalog);
    }
 
Example 12
Project: lams   File: IsolationLevelDataSourceAdapter.java   View Source Code Vote up 5 votes
/**
 * Applies the current isolation level value and read-only flag
 * to the returned Connection.
 * @see #getCurrentIsolationLevel()
 * @see #getCurrentReadOnlyFlag()
 */
@Override
protected Connection doGetConnection(String username, String password) throws SQLException {
	Connection con = super.doGetConnection(username, password);
	Boolean readOnlyToUse = getCurrentReadOnlyFlag();
	if (readOnlyToUse != null) {
		con.setReadOnly(readOnlyToUse);
	}
	Integer isolationLevelToUse = getCurrentIsolationLevel();
	if (isolationLevelToUse != null) {
		con.setTransactionIsolation(isolationLevelToUse);
	}
	return con;
}
 
Example 13
Project: nh-micro   File: MicroXaDataSource.java   View Source Code Vote up 5 votes
public void init() throws Exception{
	for(int i=0;i<minSize;i++){
		Connection connection=DriverManager.getConnection(url, username, password); 
		count.incrementAndGet();
		connection.setAutoCommit(false);
		connection.setTransactionIsolation(level);	
		pool.add(connection);
	}
	if(delayToRollFlag){
		MicroConnDelayHandler microDelayHandler=new MicroConnDelayHandler();
		microDelayHandler.dataSourceId=dataSourceId;
		microExpireCache.setMicroDelayHandler(microDelayHandler);
		microExpireCache.init();
	}
}
 
Example 14
Project: sstore-soft   File: ManagedPoolDataSource.java   View Source Code Vote up 4 votes
private Connection wrapConnectionAndMarkAsInUse(
        PooledConnection pooledConnection) throws SQLException {

    pooledConnection = assureValidConnection(pooledConnection);

    Connection conn = pooledConnection.getConnection();

    if (doResetAutoCommit) {
        conn.setAutoCommit(isAutoCommit);
    }

    if (doResetReadOnly) {
        conn.setReadOnly(isReadOnly);
    }

    if (doResetTransactionIsolation) {
        conn.setTransactionIsolation(transactionIsolation);
        /* TESING ONLY!!
        System.err.println("<<<<<<<<< ISO LVL => " + transactionIsolation
        + " >>>>>>>>>>>>");
        */
    }

    if (doResetCatalog) {
        conn.setCatalog(catalog);
        /* TESTING ONLY!
        System.err.println("<<<<<<<<< CAT => " + catalog
        + " >>>>>>>>>>>>");
        */
    }

    if (validationQuery != null) {

        // End-to-end test before return the Connection.
        java.sql.ResultSet rs = null;

        try {
            rs = conn.createStatement().executeQuery(validationQuery);

            if (!rs.next()) {
                throw new SQLException("0 rows returned");
            }
        } catch (SQLException se) {
            closePhysically(pooledConnection,
                            "Closing non-validating pooledConnection.");

            throw new SQLException("Validation query failed: "
                                   + se.getMessage());
        } finally {
            if (rs != null) {
                rs.close();
            }
        }
    }
    this.connectionsInUse.add(pooledConnection);

    SessionConnectionWrapper sessionWrapper =
        new SessionConnectionWrapper(pooledConnection.getConnection());

    this.sessionConnectionWrappers.put(pooledConnection, sessionWrapper);

    return sessionWrapper;
}
 
Example 15
Project: aliyun-maxcompute-data-collectors   File: OracleManager.java   View Source Code Vote up 4 votes
/**
 * Create a connection to the database; usually used only from within
 * getConnection(), which enforces a singleton guarantee around the
 * Connection object.
 *
 * Oracle-specific driver uses READ_COMMITTED which is the weakest
 * semantics Oracle supports.
 */
protected Connection makeConnection() throws SQLException {

  Connection connection;
  String driverClass = getDriverClass();

  try {
    Class.forName(driverClass);
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Could not load db driver class: "
        + driverClass);
  }

  String username = options.getUsername();
  String password = options.getPassword();
  String connectStr = options.getConnectString();

  try {
    connection = CACHE.getConnection(connectStr, username);
  } catch (SQLException e) {
    connection = null;
    LOG.debug("Cached connecion has expired.");
  }

  if (null == connection) {
    // Couldn't pull one from the cache. Get a new one.
    LOG.debug("Creating a new connection for "
            + connectStr + ", using username: " + username);
    Properties connectionParams = options.getConnectionParams();
    if (connectionParams != null && connectionParams.size() > 0) {
      LOG.debug("User specified connection params. "
                + "Using properties specific API for making connection.");

      Properties props = new Properties();
      if (username != null) {
        props.put("user", username);
      }

      if (password != null) {
        props.put("password", password);
      }

      props.putAll(connectionParams);
      connection = DriverManager.getConnection(connectStr, props);
    } else {
      LOG.debug("No connection paramenters specified. "
              + "Using regular API for making connection.");
      if (username == null) {
        connection = DriverManager.getConnection(connectStr);
      } else {
        connection = DriverManager.getConnection(
                            connectStr, username, password);
      }
    }
  }

  // We only use this for metadata queries. Loosest semantics are okay.
  connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

  // Setting session time zone
  setSessionTimeZone(connection);

  // Rest of the Sqoop code expects that the connection will have be running
  // without autoCommit, so we need to explicitly set it to false. This is
  // usually done directly by SqlManager in the makeConnection method, but
  // since we are overriding it, we have to do it ourselves.
  connection.setAutoCommit(false);

  return connection;
}
 
Example 16
Project: parabuild-ci   File: DBCPConnectionProvider.java   View Source Code Vote up 4 votes
public Connection getConnection() throws SQLException {
	final Connection c = ds.getConnection();
	if (isolation!=null) c.setTransactionIsolation( isolation.intValue() );
	if ( c.getAutoCommit() ) c.setAutoCommit(false);
	return c;
}
 
Example 17
Project: parabuild-ci   File: C3P0ConnectionProvider.java   View Source Code Vote up 4 votes
public Connection getConnection() throws SQLException {
	final Connection c = ds.getConnection();
	if (isolation!=null) c.setTransactionIsolation( isolation.intValue() );
	if ( c.getAutoCommit() ) c.setAutoCommit(false);
	return c;
}
 
Example 18
Project: s-store   File: ManagedPoolDataSource.java   View Source Code Vote up 4 votes
private Connection wrapConnectionAndMarkAsInUse(
        PooledConnection pooledConnection) throws SQLException {

    pooledConnection = assureValidConnection(pooledConnection);

    Connection conn = pooledConnection.getConnection();

    if (doResetAutoCommit) {
        conn.setAutoCommit(isAutoCommit);
    }

    if (doResetReadOnly) {
        conn.setReadOnly(isReadOnly);
    }

    if (doResetTransactionIsolation) {
        conn.setTransactionIsolation(transactionIsolation);
        /* TESING ONLY!!
        System.err.println("<<<<<<<<< ISO LVL => " + transactionIsolation
        + " >>>>>>>>>>>>");
        */
    }

    if (doResetCatalog) {
        conn.setCatalog(catalog);
        /* TESTING ONLY!
        System.err.println("<<<<<<<<< CAT => " + catalog
        + " >>>>>>>>>>>>");
        */
    }

    if (validationQuery != null) {

        // End-to-end test before return the Connection.
        java.sql.ResultSet rs = null;

        try {
            rs = conn.createStatement().executeQuery(validationQuery);

            if (!rs.next()) {
                throw new SQLException("0 rows returned");
            }
        } catch (SQLException se) {
            closePhysically(pooledConnection,
                            "Closing non-validating pooledConnection.");

            throw new SQLException("Validation query failed: "
                                   + se.getMessage());
        } finally {
            if (rs != null) {
                rs.close();
            }
        }
    }
    this.connectionsInUse.add(pooledConnection);

    SessionConnectionWrapper sessionWrapper =
        new SessionConnectionWrapper(pooledConnection.getConnection());

    this.sessionConnectionWrappers.put(pooledConnection, sessionWrapper);

    return sessionWrapper;
}
 
Example 19
Project: fresco_floodlight   File: JavaDBStorageEngine.java   View Source Code Vote up 4 votes
private Connection getConnection() throws SQLException {
    Connection conn = dataSource.getPooledConnection().getConnection();
    conn.setTransactionIsolation(Connection.
                                 TRANSACTION_READ_COMMITTED);
    return conn;
}
 
Example 20
Project: aliyun-maxcompute-data-collectors   File: OracleConnectionFactory.java   View Source Code Vote up 3 votes
public static void initializeOracleConnection(Connection connection,
    org.apache.hadoop.conf.Configuration conf) throws SQLException {

  connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

  connection.setAutoCommit(false);

  OraOopOracleQueries.setConnectionTimeZone(connection, conf);

  setSessionClientInfo(connection, conf);

  OraOopOracleQueries.setJdbcFetchSize(connection, conf);

  executeOraOopSessionInitializationStatements(connection, conf);
}