Java Code Examples for java.sql.Connection#rollback()

The following examples show how to use java.sql.Connection#rollback() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Test 47 multiple tests for getSavepointId()
 */
public void xtestGetSavepoint() throws SQLException {
    Connection con = getConnection();
    Savepoint savepoint1 = con.setSavepoint();
    Savepoint savepoint2 = con.setSavepoint();
    savepoint1.getSavepointId();
    savepoint2.getSavepointId();
    con.releaseSavepoint(savepoint2);
    savepoint2 = con.setSavepoint();
    savepoint2.getSavepointId();
    con.commit();
    savepoint2 = con.setSavepoint();
    savepoint2.getSavepointId();
    con.rollback();
    savepoint2 = con.setSavepoint();
    savepoint2.getSavepointId();
    con.rollback();
}
 
Example 2
Source Project: gemfirexd-oss   File: SQLDistTxTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void rollback(Connection conn) {
  boolean isTicket48177fixed = false;
  if (conn == null)
    return;
  try {
    conn.rollback();
  } catch (SQLException se) {
    if (isEdge && isHATest && !isTicket48177fixed
        && SQLHelper.gotTXNodeFailureException(se)) {
      Log
          .getLogWriter()
          .info(
              "got node failure exception during Tx due to #48177, continue the testing");
    } else
      SQLHelper.handleSQLException(se);
  }
}
 
Example 3
public void testSharedLocks2()
    throws SQLException 
{
    Statement s = createStatement();
    ResultSet rs = s.executeQuery("select * from t1");
    scrollForward(rs);
    Connection con2 = openDefaultConnection();
    Statement s2 = con2.createStatement();
    try {
        final ResultSet rs2 = s2.executeQuery("select * from t1");
        scrollForward(rs2);
    } finally {
        rs.close();
        con2.rollback();
        con2.close();
    }
    s.close();
}
 
Example 4
/**
 * Test that we don't get an NPE when re-using a PreparedStatement
 * on a temp table declared and then rolled back. See DERBY_6189.
 */
public  void    test_derby_6189() throws Exception
{
    Connection  conn = getConnection();

    conn.prepareStatement
        ( "DECLARE GLOBAL TEMPORARY TABLE SESSION.t6189( c21 int, c22 int) not logged on commit preserve rows" )
        .execute();        
    PreparedStatement pStmtInsert = conn.prepareStatement( "insert into SESSION.t6189 values (23, 1)" );

    pStmtInsert.execute();

    conn.rollback();

    assertStatementError("42X05", pStmtInsert); 
}
 
Example 5
Source Project: gemfirexd-oss   File: ConcurrencyTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSharedAndUpdateLocks2()
    throws SQLException 
{
    Statement s = createStatement(ResultSet.TYPE_FORWARD_ONLY, 
                                      ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = s.executeQuery("select * from t1 for update");
    scrollForward(rs);
    Connection con2 = openDefaultConnection();
    Statement s2 = con2.createStatement(ResultSet.TYPE_FORWARD_ONLY, 
                                        ResultSet.CONCUR_READ_ONLY);
    try {
        final ResultSet rs2 = s2.executeQuery("select * from t1");
        scrollForward(rs2);
    } finally {
        rs.close();
        con2.rollback();
        con2.close();
    }
    s.close();
}
 
Example 6
public static void updateRank() {
    FileoutputUtil.log("开始更新玩家排名...");
    long startTime = System.currentTimeMillis();
    loadJobCommands();
    Connection con = DatabaseConnection.getConnection();
    try {
        con.setAutoCommit(false);
        updateRanking(con);
        updatePokemonRatio(con);
        updateItemSearch(con);
        con.commit();
        con.setAutoCommit(true);
    } catch (Exception ex) {
        try {
            con.rollback();
            con.setAutoCommit(true);
            FileoutputUtil.outputFileError(FileoutputUtil.ScriptEx_Log, ex);
            System.err.println("更新玩家排名出错");
        } catch (SQLException ex2) {
            FileoutputUtil.outputFileError(FileoutputUtil.ScriptEx_Log, ex2);
            System.err.println("Could not rollback unfinished ranking transaction");
        }
    }
    FileoutputUtil.log(new StringBuilder().append("玩家排名更新完成 耗时: ").append((System.currentTimeMillis() - startTime) / 1000L).append(" 秒..").toString());
}
 
Example 7
/**
 * Delete the datamodel
 */
protected void tearDown() 
    throws Exception
{
    try {
        Connection con = getConnection();
        con.rollback();
        con.createStatement().execute("drop table t1");
        con.commit();
    } catch (SQLException e) {
        printStackTrace(e);
    }
    super.tearDown();
}
 
Example 8
/**
 * Test that update locks are downgraded to shared locks
 * after repositioning.
 * This test fails with Derby
 */
public void testUpdateLockDownGrade1()
    throws SQLException 
{
    Statement s = createStatement(ResultSet.TYPE_FORWARD_ONLY, 
                                      ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = s.executeQuery("select * from t1 for update");
    
    // After navigating through the resultset, 
    // presumably all rows are locked with shared locks
    while (rs.next());
    
    // Now open up a connection
    Connection con2 = openDefaultConnection();
    Statement s2 = con2.createStatement(ResultSet.TYPE_FORWARD_ONLY, 
                                        ResultSet.CONCUR_UPDATABLE);
    
    ResultSet rs2 = s2.executeQuery("select * from t1 for update");
    try {
        rs2.next(); // We should be able to get a update lock here.
    } catch (SQLException e) {
        assertEquals("Unexpected SQL state",  LOCK_TIMEOUT_SQL_STATE,
                     e.getSQLState());
        return;
    } finally {
        con2.rollback();
    }
    assertTrue("Expected Derby to hold updatelocks in RR mode", false);
    
    s2.close();
    con2.close();
    
    s.close();
}
 
Example 9
/**
 * Revoke the transaction when catch then sql transaction errors.
 *
 * @param dbConnection database connection.
 */
private static void rollbackTransaction(Connection dbConnection) {

    try {
        if (dbConnection != null) {
            dbConnection.rollback();
        }
    } catch (SQLException e1) {
        log.error("An error occurred while rolling back transactions. ", e1);
    }
}
 
Example 10
/**
 * issue a rollback when SQLException se occurs. If SQLException ouccurs when
 * rollback, the new SQLException will be added into the chain of se.
 */
private static void rollBackAndThrowSQLException(Connection conn,
    SQLException se) throws SQLException {
  try {
    conn.rollback();
  } catch (SQLException e) {
    se.setNextException(e);
  }
  throw se;
}
 
Example 11
/**
 * Assert that a user has trigger execute privilege on a given table / column
 * @param hasPrivilege whether or not the user has the privilege
 * @param user the user to check
 * @param schema the schema to check
 * @param table the table to check
 * @throws SQLException throws all exceptions
 */
public void assertTriggerPrivilege(boolean hasPrivilege, String user, String schema, String table) throws SQLException {
	
	Connection c = openUserConnection(user);
	c.setAutoCommit(false);
	
	Statement s = c.createStatement();
	try {
	    int i = s.executeUpdate("create trigger \"" + table + "Trig\" after insert on " +
	    		              schema + "." + table + " for each row values 1");
	    if (hasPrivilege)
	    {
	        assertEquals(0, i); 
	    }
        if (!hasPrivilege)
            fail("expected no TRIGGER permission on table");

	} catch (SQLException e) {
		if (!hasPrivilege) {
			assertSQLState("42500", e);
		} else {
			e.printStackTrace();
			fail("Unexpected lack of trigger privilege on " + schema + "." + table + " by " + user);
		}
	}
	
	c.rollback();
    s.close();
	c.close();

	assertPrivilegeMetadata(hasPrivilege, "TRIGGER", user, schema, table, null);
 
}
 
Example 12
public void createSqlTable(Connection conn, boolean generateOnly,
  int count, String table, ColumnGenerator... extraCols)
  throws Exception {
  PreparedStatement statement = conn.prepareStatement(
    getSqlDropTableStatement(table),
    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  try {
    statement.executeUpdate();
    conn.commit();
  } catch (SQLException sqle) {
    conn.rollback();
  } finally {
    statement.close();
  }
  statement = conn.prepareStatement(
    getSqlCreateTableStatement(table, extraCols),
    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  try {
    statement.executeUpdate();
    conn.commit();
  } finally {
    statement.close();
  }
  if (!generateOnly) {
    loadSqlTable(conn, table, count, extraCols);
  }
}
 
Example 13
Source Project: gemfirexd-oss   File: TransactionDUnit.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Jag's simple test case.
 * 
 * @throws Exception
 */
public void testJagsUseCase_timeInserts() throws Exception {
  // reduce logs
  reduceLogLevelForTest("warning");

  startVMs(0, 1);
  final int netPort = startNetworkServer(1, null, null);
  final Connection conn = TestUtil.getNetConnection(netPort,
      "/;user=app;password=app", null);
  Statement s = conn.createStatement();
  try {
    s.executeUpdate("drop table securities");
  } catch (Exception e) {
  }

  s.executeUpdate("create table securities ( sec_id integer not null "
      + "constraint sec_pk primary key, symbol varchar(30), "
      + "price double precision, exchange varchar(30),count integer)"+ getSuffix());
  conn.setTransactionIsolation(getIsolationLevel());
  conn.setAutoCommit(false);
  getLogWriter().info(" Warming up ...");

  dumpIntoTable(conn, 1000);
  conn.rollback();
  long begin = System.nanoTime();
  dumpIntoTable(conn, 10000);
  conn.commit();
  long end = System.nanoTime();
  getLogWriter().info("Time to execute 10k operations"
      + (end - begin) / 1000000 + " millis");
}
 
Example 14
Source Project: gemfirexd-oss   File: GrantRevokeTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Test grant statements before, during, and after a rolled-back
 * transaction
 */
public void DISABLED_42972_testGrantRollbackAndCommit() throws SQLException {

  // GemStone changes BEGIN
  if (isAvoidGFXDBugs()) {
    fail("Failing test due to ticket 42972 (corrupts test environment for other testcases)");
  }
  // GemStone changes END

  // NOTE: grantrevoke.java originally used S2.F2 for the function
  // below, but the signature on the function didn't match the
  // declaration, so was not used properly. Have substituted
  // function S1.F1 here to get the testcase to pass.

  // NOTE 2: executing the grant statements on the owner connection
  //         leads to a lock timeout when asserting any privilege?

  Connection oc = openUserConnection(users[0]);
  oc.setAutoCommit(false);
  oc.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

  // set up some privileges and check them
  grant(oc, "select", "s2", "t2", "public");
  oc.commit();

    assertSelectPrivilege(true, users[3], "S2", "T2", null);
    assertUpdatePrivilege(false, users[3], "S2", "T2", null);
    assertSelectPrivilege(false, users[1], "S2", "T3", new String[] {"C2"});
    assertDeletePrivilege(false, users[1], "S2", "T3");
    assertTriggerPrivilege(false, users[2], "S2", "T2");
    assertFunctionPrivilege(false, users[1], "S1", "F1", false);

  // alter some privileges, assert that they were granted.
    grant(oc, "select(c2),delete", "s2", "t3", users[1]);
    grant(oc, "trigger", "s2", "t2", "public");
  grant(oc, "execute", "function s1", "f1", users[1]);
    // the following asserts fail due to lock timeout
  //assertSelectPrivilege(true, users[1], "s2", "t3", new String[] {"C2"});
    //assertDeletePrivilege(true, users[1], "s2", "t3");
    //assertTriggerPrivilege(true, users[2], "S2", "T2");
    //assertFunctionPrivilege(true, users[1], "S1", "F1", false);

    // roll it back and assert the privileges were not granted.
    oc.rollback();
    assertSelectPrivilege(false, users[1], "S2", "T3", new String[] {"C2"});
    assertDeletePrivilege(false, users[1], "S2", "T3");
    assertTriggerPrivilege(false, users[2], "S2", "T2");
    assertFunctionPrivilege(false, users[1], "S1", "F1", false);

    // do it again...
    grant(oc, "select(c2),delete", "s2", "t3", users[1]);
    grant(oc, "trigger", "s2", "t2", "public");
  grant(oc, "execute", "function s1", "f1", users[1]);
    // the following asserts fail due to lock timeout
  //assertSelectPrivilege(true, users[1], "S2", "T3", new String[] {"C2"});
    //assertDeletePrivilege(true, users[1], "S2", "T3");
    //assertTriggerPrivilege(true, users[2], "S2", "T2");
    //assertFunctionPrivilege(true, users[1], "S1", "F1", false);

    // commit and ensure the permissions are correct
    oc.commit();
    assertSelectPrivilege(true, users[1], "S2", "T3", new String[] {"C2"});
    assertDeletePrivilege(true, users[1], "S2", "T3");
    assertTriggerPrivilege( true, users[2], "S2", "T2");
    assertFunctionPrivilege( true, users[1], "S1", "F1", false);

  // remove any permissions we granted
  revoke(oc, "select", "s2", "t2", "public");
  revoke(oc, "select(c2),delete", "s2", "t3", users[1]);
    revoke(oc, "trigger", "s2", "t2", "public");
  revoke(oc, "execute", "function s1", "f1", users[1]);
  oc.commit();
  oc.setAutoCommit(false);
    assertSelectPrivilege(false, users[3], "S2", "T2", null);
    assertUpdatePrivilege(false, users[3], "S2", "T2", null);
    assertSelectPrivilege(false, users[1], "S2", "T3", new String[] {"C2"});
    assertDeletePrivilege(false, users[1], "S2", "T3");
    assertTriggerPrivilege(false, users[2], "S2", "T2");
    assertFunctionPrivilege(false, users[1], "S1", "F1", false);

  oc.close();

}
 
Example 15
@Test
public void testAcquireLock_Multi() throws Exception {
    Assume.assumeFalse(skipTests() || dataSource == null);

    Connection con = getConnection();
    try {
        PersistentLockManagerDialect x = createImplementation();
        String _lockId = "4711";

        Date _insertTS1 = new Date(System.currentTimeMillis() - 5000);
        Date _insertTS2 = new Date(System.currentTimeMillis() - 4000);
        Date _insertTS3 = new Date(System.currentTimeMillis() - 3000);
        String correlationId1 = UUID.randomUUID().toString();
        String workflowInstanceId1 = UUID.randomUUID().toString();
        String correlationId2 = UUID.randomUUID().toString();
        String workflowInstanceId2 = UUID.randomUUID().toString();
        String correlationId3 = UUID.randomUUID().toString();
        String workflowInstanceId3 = UUID.randomUUID().toString();

        String rv = x.acquireLock(_lockId, workflowInstanceId1, correlationId1, _insertTS1, con);
        org.junit.Assert.assertNull(rv);
        Thread.sleep(5);

        rv = x.acquireLock(_lockId, workflowInstanceId1, correlationId1, _insertTS1, con);
        org.junit.Assert.assertNull(rv);
        Thread.sleep(5);

        rv = x.acquireLock(_lockId, workflowInstanceId2, correlationId2, _insertTS2, con);
        org.junit.Assert.assertEquals(correlationId2, rv);
        Thread.sleep(5);

        rv = x.acquireLock(_lockId, workflowInstanceId3, correlationId3, _insertTS3, con);
        org.junit.Assert.assertEquals(correlationId3, rv);
        Thread.sleep(5);

        rv = x.releaseLock(_lockId, workflowInstanceId1, con);
        org.junit.Assert.assertEquals(correlationId2, rv);
        Thread.sleep(5);

        rv = x.releaseLock(_lockId, workflowInstanceId2, con);
        org.junit.Assert.assertEquals(correlationId3, rv);
        Thread.sleep(5);

        rv = x.releaseLock(_lockId, workflowInstanceId3, con);
        org.junit.Assert.assertNull(rv);

    } finally {
        con.rollback();
        JdbcUtils.closeConnection(con);
    }
}
 
Example 16
Source Project: gemfirexd-oss   File: ConcurrencyTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Test what happens if you update a tuple which has been modified by 
 * another transaction (in this case the same column)
 **/
public void testUpdateModifiedTuple2()
    throws SQLException 
{
    getConnection().setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    Statement s = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
                                      ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = s.executeQuery("select * from t1");
    rs.next(); // Point to first tuple
    println("T1: Read next Tuple:(" + rs.getInt(1) + "," +
            rs.getInt(2) + "," +
            rs.getInt(3) + ")");
    int firstKey = rs.getInt(1);
    rs.next(); // Go to next
    println("T1: Read next Tuple:(" + rs.getInt(1) + "," +
            rs.getInt(2) + "," +
            rs.getInt(3) + ")");
    Connection con2 = openDefaultConnection();
    con2.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    try {
        PreparedStatement ps2 = con2.prepareStatement
            ("update t1 set b=? where id=?");
        ps2.setInt(1, 999);
        ps2.setInt(2, firstKey);
        assertEquals("Expected one record to be updated", 1, 
                     ps2.executeUpdate());
        println("T2: Updated b=999 where id=" + firstKey);
        con2.commit();
        println("T2: commit");
    } catch (SQLException e) {
        con2.rollback();
        throw e;
    }
    rs.previous(); // Go back to first tuple
    println("T1: Read previous Tuple:(" + rs.getInt(1) + "," +
            rs.getInt(2) + "," +
            rs.getInt(3) + ")");
    rs.updateInt(3, 9999);
    rs.updateRow();
    println("T1: updated column 3, to value=9999");
    commit();
    println("T1: commit");
    rs = s.executeQuery("select * from t1");
    while (rs.next()) {
        println("T3: Read next Tuple:(" + rs.getInt(1) + "," +
                rs.getInt(2) + "," +
                rs.getInt(3) + ")");
        
    }
    con2.close();
}
 
Example 17
Source Project: gemfirexd-oss   File: BatchUpdateTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testTransactionErrorBatch() throws SQLException {

        // conn is just default connection
        Connection conn = getConnection();
        Connection conn2 = openDefaultConnection();
        conn.setAutoCommit(false);
        conn2.setAutoCommit(false);
        // GemStone changes BEGIN
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        conn2.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        // GemStone changes END
        Statement stmt = conn.createStatement();
        Statement stmt2 = conn2.createStatement();

        int[] updateCount = null;

        println("Negative Statement: statement testing time out" +
            " while getting the lock in the batch");

        stmt.execute("insert into t1 values(1)");
        stmt2.execute("insert into t1 values(2)");

        stmt.addBatch("update t1 set c1=3 where c1=2");
        stmt2.addBatch("update t1 set c1=4 where c1=1");

        try
        {
            stmt.executeBatch();
            fail ("Batch is expected to fail");
            updateCount = stmt2.executeBatch();
        } catch (BatchUpdateException bue) {
            /* Ensure the exception is time out while getting lock */
            if (usingEmbedded())
                assertSQLState("40XL1", bue);
            else if (usingDerbyNetClient())
                assertSQLState("XJ208", bue);
            updateCount = ((BatchUpdateException)bue).getUpdateCounts();
            if (updateCount != null) {
                if (usingEmbedded())
                    assertEquals("first statement in the batch caused time out" +
                        " while getting the lock, there should be no update count",
                        0, updateCount.length);
                else if (usingDerbyNetClient())
                    /* first statement in the batch caused time out while getting
                     *  the lock, there should be 1 update count of -3 */
                    assertBatchUpdateCounts(new int[] {-3}, updateCount);
            }
        }
        conn.rollback();
        conn2.rollback();
        stmt.clearBatch();
        stmt2.clearBatch();
        stmt.close();
        stmt2.close();
        commit();
        conn2.close();
    }
 
Example 18
Source Project: gemfirexd-oss   File: ConcurrencyTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Test what happens if you update a deleted + purged tuple.
 * The transaction which deletes the tuple, will also
 * ensure that the tuple is purged from the table, not only marked
 * as deleted.
 **/
public void testUpdatePurgedTuple1()
    throws SQLException
{
    getConnection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    Statement s = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
                                      ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = s.executeQuery("select * from t1");
    rs.next();
    int firstKey = rs.getInt(1);
    println("T1: Read next Tuple:(" + rs.getInt(1) + "," +
            rs.getInt(2) + "," +
            rs.getInt(3) + ")");
    int lastKey = firstKey;
    while (rs.next()) {
        lastKey = rs.getInt(1);
        println("T1: Read next Tuple:(" + rs.getInt(1) + "," +
                rs.getInt(2) + "," +
                rs.getInt(3) + ")");
    }
    
    Connection con2 = openDefaultConnection();
    con2.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    try {
        PreparedStatement ps2 = con2.prepareStatement
            ("delete from t1 where id=? or id=?");
        ps2.setInt(1, firstKey);
        ps2.setInt(2, lastKey);
        assertEquals("Expected two records to be deleted", 
                     2, ps2.executeUpdate());
        println("T2: Deleted records with id=" + firstKey + " and id=" + 
                lastKey);
        con2.commit();
        println("T2: commit");
        ps2 = con2.prepareStatement
            ("call SYSCS_UTIL.INPLACE_COMPRESS_TABLE(?,?,?,?,?)");
        ps2.setString(1, "APP"); // schema
        ps2.setString(2, "T1");  // table name
        ps2.setInt(3, 1); // purge
        ps2.setInt(4, 0); // defragment rows
        ps2.setInt(5, 0); // truncate end
        println("T3: call SYSCS_UTIL.INPLACE_COMPRESS_TABLE");
        println("T3: purges deleted records");
        ps2.executeUpdate();
        con2.commit();
        println("T3: commit");
    } catch (SQLException e) {
        con2.rollback();
        throw e;
    }
    rs.first(); // Go to first tuple
    println("T1: Read first Tuple:(" + rs.getInt(1) + "," +
            rs.getInt(2) + "," +
            rs.getInt(3) + ")");
    rs.updateInt(2, 3);
    println("T1: updateInt(2, 3);");
    rs.updateRow();
    println("T1: updateRow()");
    rs.last(); // Go to last tuple
    println("T1: Read last Tuple:(" + rs.getInt(1) + "," +
            rs.getInt(2) + "," +
            rs.getInt(3) + ")");
    rs.updateInt(2, 3);
    println("T1: updateInt(2, 3);");
    rs.updateRow();
    println("T1: updateRow()");
    commit();
    println("T1: commit");
    rs = s.executeQuery("select * from t1");
    println("T3: select * from table");
    while (rs.next()) {
        println("T3: Read next Tuple:(" + rs.getInt(1) + "," +
                rs.getInt(2) + "," +
                rs.getInt(3) + ")");
        
    }
    
    con2.close();
    s.close();
}
 
Example 19
Source Project: gemfirexd-oss   File: ShutdownDatabase.java    License: Apache License 2.0 4 votes vote down vote up
private static void testTwiceRollbacked()
	throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
	
	final String dbname = "testTwiceRollbackedDB";
	Connection conn = null;

	
	try{
		conn = openConnectionToNewDatabase(dbname);
		createTestTable(conn);

		conn.setAutoCommit(false);
		insertIntoTestTable(conn,
				    1,
				    1000);
		conn.rollback();
		insertIntoTestTable(conn,
				    1001,
				    999);
		conn.rollback();
		
		shutdownDatabase(dbname);
		
	}catch(SQLException e){
		verifyShutdownError(e);
	}
	
	
	conn = null;

	try{
		conn = reopenConnectionToDatabase(dbname);
		countRowInTestTable(conn);
		
	}finally{
		if(conn != null){
			conn.close();
			conn = null;
		}
	}
	
}
 
Example 20
Source Project: gemfirexd-oss   File: TransactionDUnit.java    License: Apache License 2.0 4 votes vote down vote up
public void testBulkTransactionalUpdatesRollbackAndCommitClientServerReplicateTable()
    throws Exception {

  final int netPort = startNetworkServer(1, null, null);
  final Connection conn = TestUtil.getNetConnection(netPort,
      "/;user=app;password=app", null);
  Statement st = conn.createStatement();
  st.execute("create schema trade");

  st.execute("create table trade.securities (sec_id int not null, "
      + "symbol varchar(10) not null, price decimal (30, 20), "
      + "exchange varchar(10) not null, tid int, "
      + "constraint sec_pk primary key (sec_id) ) " + " replicate "+ getSuffix());

  conn.setTransactionIsolation(getIsolationLevel());
  conn.setAutoCommit(false);
  final int numRows = 5;
  PreparedStatement ps = conn
      .prepareStatement("insert into trade.securities values "
          + "(?, ?, ?, ?, ?)");
  for (int i = 0; i < numRows; i++) {
    ps.setInt(1, i);
    ps.setString(2, "XXXX" + i);
    ps.setDouble(3, i);
    ps.setString(4, "nasdaq");
    ps.setInt(5, i);
    ps.executeUpdate();
  }
  conn.commit();

  PreparedStatement psUpdate = conn
      .prepareStatement("update trade.securities "
          + "set symbol = ? where sec_id = ? and tid = ?");
  for (int i = 0; i < numRows; i++) {
    psUpdate.setString(1, "YYY" + i);
    psUpdate.setInt(2, i);
    psUpdate.setInt(3, i);
    psUpdate.executeUpdate();
  }
  // psUpdate.executeUpdate();
  // InternalDistributedSystem.getAnyInstance().getLogWriter().info("XXXX update is done");
  ResultSet rs = st.executeQuery("select * from trade.securities");
  int numRowsReturned = 0;
  while (rs.next()) {
    assertTrue("Got" + rs.getString("SYMBOL").trim(),
        (rs.getString("SYMBOL").trim()).startsWith("YYY"));
    numRowsReturned++;
  }
  assertEquals("Expected " + numRows + " row but found " + numRowsReturned,
      numRows, numRowsReturned);
  conn.rollback();
  // now commit, should be an empty tran.
  conn.commit();
  rs = st.executeQuery("select * from trade.securities");

  int numUpdates = 0;
  while (rs.next()) {
    assertTrue("Got " + rs.getString("SYMBOL").trim(), rs.getString("SYMBOL")
        .trim().startsWith("XXXX"));
    numUpdates++;
  }
  assertEquals(numRows, numUpdates);
  rs.close();

  for (int i = 0; i < numRows; i++) {
    psUpdate.setString(1, "YYY" + i);
    psUpdate.setInt(2, i);
    psUpdate.setInt(3, i);
    psUpdate.executeUpdate();
  }
  conn.commit();

  // verify.
  rs = st.executeQuery("select * from trade.securities");
  numUpdates = 0;
  while (rs.next()) {
    assertTrue("Got " + rs.getString("SYMBOL").trim(), rs.getString("SYMBOL")
        .trim().startsWith("YYY"));
    numUpdates++;
  }
  assertEquals(numRows, numUpdates);

  conn.commit();
  rs.close();
  st.close();
  psUpdate.close();
  ps.close();
  conn.close();
}