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

The following are Jave code examples for showing how to use commit() 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: message-broker   File: RdbmsCoordinationDaoImpl.java   View Source Code Vote up 6 votes
/**
 * Method to update the node heartbeat value to the current time.
 *
 * @param nodeId local node ID
 * @return true if the update is successful, false otherwise
 * @throws CoordinationException if an error is detected while updating the node heartbeat.
 */
public boolean updateNodeHeartbeat(String nodeId) throws CoordinationException {
    Connection connection = null;
    PreparedStatement preparedStatementForNodeUpdate = null;
    String task = RdbmsCoordinationConstants.TASK_UPDATE_NODE_HEARTBEAT;
    try {
        connection = getConnection();
        preparedStatementForNodeUpdate = connection.prepareStatement(
                RdbmsCoordinationConstants.PS_UPDATE_NODE_HEARTBEAT);
        preparedStatementForNodeUpdate.setLong(1, System.currentTimeMillis());
        preparedStatementForNodeUpdate.setString(2, nodeId);
        int updateCount = preparedStatementForNodeUpdate.executeUpdate();
        connection.commit();
        return updateCount != 0;
    } catch (SQLException e) {
        rollback(connection, task);
        throw new CoordinationException("Error occurred while " + task + ". Node ID: " + nodeId, e);
    } finally {
        close(preparedStatementForNodeUpdate, task);
        close(connection, task);
    }
}
 
Example 2
Project: the-vigilantes   File: ConnectionTest.java   View Source Code Vote up 6 votes
public void testLifecyleInterceptor() throws Exception {
    createTable("testLifecycleInterceptor", "(field1 int)", "InnoDB");
    Connection liConn = null;

    try {
        liConn = getConnectionWithProps("connectionLifecycleInterceptors=testsuite.simple.TestLifecycleInterceptor");
        liConn.setAutoCommit(false);

        liConn.createStatement().executeUpdate("INSERT INTO testLifecycleInterceptor VALUES (1)");
        liConn.commit();
        assertEquals(TestLifecycleInterceptor.transactionsBegun, 1);
        assertEquals(TestLifecycleInterceptor.transactionsCompleted, 1);
        liConn.createStatement().execute("SELECT * FROM testLifecycleInterceptor");
        assertEquals(TestLifecycleInterceptor.transactionsBegun, 2);
        // implicit commit
        liConn.createStatement().executeUpdate("CREATE TABLE testLifecycleFoo (field1 int)");
        assertEquals(TestLifecycleInterceptor.transactionsCompleted, 2);
    } finally {
        if (liConn != null) {
            liConn.createStatement().executeUpdate("DROP TABLE IF EXISTS testLifecycleFoo");
            liConn.close();
        }
    }

}
 
Example 3
Project: message-broker   File: QueueDaoImpl.java   View Source Code Vote up 6 votes
@Override
public void persist(Queue queue) throws BrokerException {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        statement = connection.prepareStatement(RDBMSConstants.PS_INSERT_QUEUE);
        statement.setString(1, queue.getName());
        statement.setBytes(2, new byte[0]);
        statement.executeUpdate();

        connection.commit();
    } catch (SQLException e) {
        throw new BrokerException("Error occurred while storing queue " + queue, e);
    } finally {
        close(connection, statement);
    }
}
 
Example 4
Project: taskana   File: ClassificationServiceImplIntExplicitTest.java   View Source Code Vote up 6 votes
@Test
public void testFindWithClassificationMapperDomainAndCategory()
    throws NotAuthorizedException, SQLException, ClassificationAlreadyExistException,
    ClassificationNotFoundException {
    Connection connection = dataSource.getConnection();
    taskanaEngineImpl.setConnection(connection);
    Classification classification1 = this.createNewClassificationWithUniqueKey("domain1", "t1");
    classification1.setCategory("category1");
    classificationService.createClassification(classification1);
    Classification classification2 = this.createNewClassificationWithUniqueKey("domain2", "t1");
    classification2.setCategory("category1");
    classificationService.createClassification(classification2);

    Classification classification3 = this.createNewClassificationWithUniqueKey("domain1", "t1");
    classification3.setCategory("category2");
    classificationService.createClassification(classification3);

    List<ClassificationSummary> list = classificationService.createClassificationQuery()
        .category("category1")
        .domain("domain1")
        .list();
    Assert.assertEquals(1, list.size());
    list = classificationService.createClassificationQuery().domain("domain1", "domain3").list();
    Assert.assertEquals(2, list.size());
    connection.commit();
}
 
Example 5
Project: aliyun-maxcompute-data-collectors   File: DirectPostgreSQLExportManualTest.java   View Source Code Vote up 6 votes
@Override
protected Connection getConnection() {
  try {
    Connection conn = dbConf.getConnection();
    conn.setAutoCommit(false);
    PreparedStatement stmt =
        conn.prepareStatement("SET extra_float_digits TO 0");
    stmt.executeUpdate();
    conn.commit();
    return conn;
  } catch (SQLException sqlE) {
    LOG.error("Could not get connection to test server: " + sqlE);
    return null;
  } catch (ClassNotFoundException cnfE) {
    LOG.error("Could not find driver class: " + cnfE);
    return null;
  }
}
 
Example 6
Project: HTAPBench   File: BenchmarkModule.java   View Source Code Vote up 6 votes
/**
 * Invoke this benchmark's database loader using the given Connection handle
 * @param conn
 */
protected final void loadDatabase(Connection conn, boolean calibrate, boolean generateFiles, String filesPath) {
    try {
        Loader loader = this.makeLoaderImpl(conn, calibrate,generateFiles,filesPath);
        if (loader != null) {
            conn.setAutoCommit(false);
            loader.load();
            conn.commit();

            if (loader.getTableCounts().isEmpty() == false) {
                LOG.info("Table Counts:\n" + loader.getTableCounts());
            }
        }
    } catch (SQLException ex) {
        throw new RuntimeException(String.format("Unexpected error when trying to load the %s database", this.benchmarkName), ex);
    }
}
 
Example 7
Project: mycat-src-1.6.1-RELEASE   File: MultiThreadSequnceTest.java   View Source Code Vote up 6 votes
private static void testSequnce(Connection theCon) throws SQLException {
	try {
		theCon.setAutoCommit(false);
		String sql = "select next value for MYCATSEQ_GLOBAL ";
		Statement stmt = theCon.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		if (rs.next()) {
			System.out.println(Thread.currentThread().getName()
					+ " get seq " + rs.getLong(1));
		} else {
			System.out.println(Thread.currentThread().getName()
					+ " can't get  seq ");
		}

		theCon.commit();
		stmt.close();
	} finally {
		theCon.close();
	}
}
 
Example 8
Project: aliyun-maxcompute-data-collectors   File: TestExportUsingProcedure.java   View Source Code Vote up 5 votes
private static void insertFunction(int id, String msg,
    SetExtraArgs setExtraArgs) throws SQLException {
  instanceForProcedure.functionCalls += 1;
  Connection con = instanceForProcedure.getConnection();

  StringBuilder sql = new StringBuilder("insert into ");
  sql.append(instanceForProcedure.getTableName());
  sql.append("(id, msg");
  for (int i = 0; i < instanceForProcedure.names.length; ++i) {
    sql.append(", ");
    sql.append(instanceForProcedure.names[i]);
  }
  sql.append(") values (");
  for (int i = 0; i < instanceForProcedure.names.length + 2; ++i) {
    sql.append("?,");
  }
  // Remove last ,
  sql = sql.delete(sql.length() - 1, sql.length());
  sql.append(")");

  PreparedStatement statement = con.prepareStatement(sql.toString());
  try {
    statement.setInt(1, id);
    statement.setString(2, msg);
    setExtraArgs.set(statement);
    statement.execute();
    con.commit();
  } finally {
    statement.close();
  }
}
 
Example 9
Project: the-vigilantes   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
public void testBug31053() throws Exception {
    Properties props = new Properties();
    props.setProperty("connectTimeout", "2000");
    props.setProperty("loadBalanceStrategy", "random");

    Connection lbConn = getLoadBalancedConnection(2, "localhost:23", props);

    lbConn.setAutoCommit(false);

    for (int i = 0; i < 10; i++) {
        lbConn.commit();
    }
}
 
Example 10
Project: parabuild-ci   File: TriggerSample.java   View Source Code Vote up 5 votes
private static void doSomeWork() throws SQLException {

        Connection conn = getConnection();
        Statement  stmt = conn.createStatement();

        conn.setAutoCommit(false);
        stmt.execute("INSERT INTO trig_test VALUES (1, 'hello')");
        stmt.execute("INSERT INTO trig_test VALUES (2, 'now what?')");
        stmt.execute("INSERT INTO trig_test VALUES (3, 'unchangable')");
        stmt.execute("INSERT INTO trig_test VALUES (4, 'goodbye')");
        conn.commit();
        dumpTable("trig_test");
        stmt.execute("UPDATE trig_test SET value = 'all done'");
        conn.commit();
        dumpTable("trig_test");
        stmt.execute("DELETE FROM trig_test");
        conn.rollback();
        dumpTable("trig_test");

        try {
            stmt.execute("INSERT INTO trig_test VALUES(11, 'whatever')");
        } catch (SQLException se) {
            se.printStackTrace();
        }

        stmt.execute("INSERT INTO trig_test VALUES(10, 'whatever')");
        conn.commit();
        dumpTable("trig_test");
        stmt.close();
        conn.close();
    }
 
Example 11
Project: aliyun-maxcompute-data-collectors   File: CubridCompatTest.java   View Source Code Vote up 5 votes
@Override
protected void dropTableIfExists(String table) throws SQLException {
  Connection conn = getManager().getConnection();
  PreparedStatement statement = conn.prepareStatement(
      "DROP TABLE IF EXISTS "
      + table, ResultSet.TYPE_FORWARD_ONLY,
      ResultSet.CONCUR_READ_ONLY);
  try {
    statement.executeUpdate();
    conn.commit();
  } finally {
    statement.close();
  }
}
 
Example 12
Project: aliyun-maxcompute-data-collectors   File: SQLServerParseMethodsManualTest.java   View Source Code Vote up 5 votes
/**
 * Drop a table if it already exists in the database.
 *
 * @param table
 *            the name of the table to drop.
 * @throws SQLException
 *             if something goes wrong.
 */
protected void dropTableIfExists(String table) throws SQLException {
  Connection conn = getManager().getConnection();
  String sqlStmt = "IF OBJECT_ID('" + table
      + "') IS NOT NULL  DROP TABLE " + table;

  PreparedStatement statement = conn.prepareStatement(sqlStmt,
      ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  try {
    statement.executeUpdate();
    conn.commit();
  } finally {
    statement.close();
  }
}
 
Example 13
Project: taskana   File: ClassificationServiceImplIntExplicitTest.java   View Source Code Vote up 5 votes
@Test
public void testFindWithClassificationMapperCustomAndCategory()
    throws NotAuthorizedException, SQLException, ClassificationAlreadyExistException,
    ClassificationNotFoundException {
    Connection connection = dataSource.getConnection();
    taskanaEngineImpl.setConnection(connection);
    Classification classification1 = this.createNewClassificationWithUniqueKey("", "t1");
    classification1.setDescription("DESC1");
    classification1.setCategory("category1");
    classificationService.createClassification(classification1);
    Classification classification2 = this.createNewClassificationWithUniqueKey("", "t1");
    classification2.setDescription("DESC1");
    classification2.setCustom1("custom1");
    classification2.setCategory("category1");
    classificationService.createClassification(classification2);
    Classification classification3 = this.createNewClassificationWithUniqueKey("", "t1");
    classification3.setCustom1("custom2");
    classification3.setCustom2("custom1");
    classification3.setCategory("category2");
    classificationService.createClassification(classification3);
    Classification classification4 = this.createNewClassificationWithUniqueKey("", "t1");
    classification4.setDescription("description2");
    classification4.setCustom8("custom2");
    classification4.setCategory("category1");
    classificationService.createClassification(classification4);

    List<ClassificationSummary> list = classificationService.createClassificationQuery()
        .descriptionLike("DESC1")
        .customFields("custom1")
        .list();
    Assert.assertEquals(1, list.size());
    list = classificationService.createClassificationQuery().customFields("custom2").list();
    Assert.assertEquals(2, list.size());
    list = classificationService.createClassificationQuery().descriptionLike("DESC1").category("category1").list();
    Assert.assertEquals(2, list.size());
    connection.commit();
}
 
Example 14
Project: metanome-algorithms   File: DatabaseUtils.java   View Source Code Vote up 5 votes
public static void close(Connection connection) {
	try {
		if (connection != null) {
			if (!connection.getAutoCommit())
				connection.commit();
			connection.close();
		}
	}
	catch (SQLException e) {
		e.printStackTrace();
	}
}
 
Example 15
Project: OpenVertretung   File: ConnectionRegressionTest.java   View Source Code Vote up 4 votes
public void testBug56429() throws Exception {
    Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
    props.setProperty("autoReconnect", "true");
    props.setProperty("socketFactory", "testsuite.UnreliableSocketFactory");

    Properties urlProps = new NonRegisteringDriver().parseURL(BaseTestCase.dbUrl, null);

    String host = urlProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
    String port = urlProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);

    props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
    props.remove(NonRegisteringDriver.NUM_HOSTS_PROPERTY_KEY);
    props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY + ".1");
    props.remove(NonRegisteringDriver.PORT_PROPERTY_KEY + ".1");

    props.setProperty("queriesBeforeRetryMaster", "50");
    props.setProperty("maxReconnects", "1");

    UnreliableSocketFactory.mapHost("master", host);
    UnreliableSocketFactory.mapHost("slave", host);

    Connection failoverConnection = null;

    try {
        failoverConnection = getConnectionWithProps("jdbc:mysql://master:" + port + ",slave:" + port + "/", props);

        String userHost = getSingleIndexedValueWithQuery(1, "SELECT USER()").toString();
        String[] userParts = userHost.split("@");

        this.rs = this.stmt.executeQuery("SHOW PROCESSLIST");

        int startConnCount = 0;

        while (this.rs.next()) {
            if (this.rs.getString("User").equals(userParts[0]) && this.rs.getString("Host").equals(userParts[1])) {
                startConnCount++;
            }
        }

        assert (startConnCount > 0);

        failoverConnection.setAutoCommit(false); // this will fail if state
                                                // not copied over

        for (int i = 0; i < 20; i++) {

            failoverConnection.commit();
        }

        this.rs = this.stmt.executeQuery("SHOW PROCESSLIST");

        int endConnCount = 0;

        while (this.rs.next()) {
            if (this.rs.getString("User").equals(userParts[0]) && this.rs.getString("Host").equals(userParts[1])) {
                endConnCount++;
            }
        }

        assert (endConnCount > 0);

        if (endConnCount - startConnCount >= 20) { // this may be bogus if run on a real system, we should probably look to see they're coming from this
                                                      // testsuite?
            fail("We're leaking connections even when not failed over");
        }
    } finally {
        if (failoverConnection != null) {
            failoverConnection.close();
        }
    }
}
 
Example 16
Project: x7   File: DaoImpl.java   View Source Code Vote up 4 votes
protected boolean refresh(Object obj, Map<String, Object> conditionMap, Connection conn) {

		@SuppressWarnings("rawtypes")
		Class clz = obj.getClass();

		Parsed parsed = Parser.get(clz);

		Map<String, Object> queryMap = BeanUtilX.getRefreshMap(parsed, obj);

		String simpleName = BeanUtil.getByFirstLower(clz.getSimpleName());
		StringBuilder sb = new StringBuilder();
		sb.append("UPDATE ").append(simpleName).append(" ");
		String sql = SqlUtil.concatRefresh(sb, parsed, queryMap, conditionMap);
		sql = BeanUtilX.mapperName(sql, parsed);

		// System.out.println("refreshOptionally: " + sql);

		boolean isNoBizTx = false;
		boolean flag = false;

		PreparedStatement pstmt = null;
		try {
			conn.setAutoCommit(false);
			pstmt = conn.prepareStatement(sql);

			isNoBizTx = Tx.isNoBizTx();
			if (!isNoBizTx) {
				Tx.add(pstmt);
			}

			int i = 1;
			for (Object value : queryMap.values()) {
				value = SqlUtil.filter(value);
				pstmt.setObject(i++, value);
			}

			/*
			 * 处理KEY
			 */
			Field keyOneF = parsed.getKeyField(X.KEY_ONE);
			SqlUtil.adpterRefreshCondition(pstmt, keyOneF, null, obj, i, conditionMap);

			flag = pstmt.executeUpdate() == 0 ? false : true;

			if (isNoBizTx) {
				conn.commit();
			}

		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
			if (isNoBizTx) {
				try {
					conn.rollback();
					System.out.println("line 1675 " + e.getMessage());
					e.printStackTrace();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			} else {
				throw new RollbackException("RollbackException: " + e.getMessage());
			}
		} finally {
			if (isNoBizTx) {
				close(pstmt);
				close(conn);
			}
		}

		return flag;
	}
 
Example 17
Project: OpenVertretung   File: ConnectionRegressionTest.java   View Source Code Vote up 4 votes
public void testBug14563127() throws Exception {
    Properties props = new Properties();
    props.setProperty("loadBalanceStrategy", ForcedLoadBalanceStrategy.class.getName());
    props.setProperty("loadBalanceBlacklistTimeout", "5000");
    props.setProperty("loadBalancePingTimeout", "100");
    props.setProperty("loadBalanceValidateConnectionOnSwapServer", "true");

    String portNumber = new NonRegisteringDriver().parseURL(dbUrl, null).getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);

    if (portNumber == null) {
        portNumber = "3306";
    }

    ForcedLoadBalanceStrategy.forceFutureServer("first:" + portNumber, -1);
    Connection conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(false);
    conn2.createStatement().execute("SELECT 1");

    // make sure second is added to active connections cache:
    ForcedLoadBalanceStrategy.forceFutureServer("second:" + portNumber, -1);
    conn2.commit();

    // switch back to first:
    ForcedLoadBalanceStrategy.forceFutureServer("first:" + portNumber, -1);
    conn2.commit();

    // kill second while still in cache:
    UnreliableSocketFactory.downHost("second");

    // force second host to be selected next time:
    ForcedLoadBalanceStrategy.forceFutureServer("second:" + portNumber, 1);

    try {
        conn2.commit(); // will be on second after this
        assertTrue("Connection should not be closed", !conn2.isClosed());
    } catch (SQLException e) {
        fail("Should not error because failure to select another server.");
    }
    conn2.close();

}
 
Example 18
Project: DBus   File: MySQLManager.java   View Source Code Vote up 4 votes
@Override
public String[] getColumnNames(String tableName) {
    Connection c = null;
    Statement s = null;
    ResultSet rs = null;
    List<String> columns = new ArrayList<String>();
    String schema=tableName.split("\\.")[0];
    tableName=tableName.split("\\.")[1];
    String listColumnsQuery = "SELECT COLUMN_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS "
          + "WHERE TABLE_SCHEMA = '" + schema + "' "
          + "  AND TABLE_NAME = '" + tableName + "' ";
    
    try {
      c = getConnection();
      s = c.createStatement();
      rs = s.executeQuery(listColumnsQuery);
      while (rs.next()) {
          String columnName=rs.getString(1);
          String columnDataType=rs.getString(2);
          if(SupportedMysqlDataType.isSupported(columnDataType)) {
              columns.add(columnName);
          }
      }
      c.commit();
    } catch (SQLException sqle) {
      try {
        if (c != null) {
          c.rollback();
        }
      } catch (SQLException ce) {
        LOG.warn("Failed to rollback transaction", ce);
      }
      LOG.warn("Failed to list columns from query: "
        + listColumnsQuery, sqle);
      throw new RuntimeException(sqle);
    }catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException re) {
          LOG.warn("Failed to close resultset", re);
        }
      }
      if (s != null) {
        try {
          s.close();
        } catch (SQLException se) {
          LOG.warn("Failed to close statement", se);
        }
      }
    }

    return columns.toArray(new String[columns.size()]);
}
 
Example 19
Project: parabuild-ci   File: TestMultipleConnections.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {

        // test for bug itme 500105 commit does not work with multiple con. FIXED
        TestMultipleConnections hs   = new TestMultipleConnections();
        Connection              con1 = hs.createObject();
        Connection              con2 = hs.createObject();
        Connection              con3 = hs.createObject();

        con1.setAutoCommit(false);

        //connection1.commit();
        con2.setAutoCommit(false);

        //connection1.commit();
        con3.setAutoCommit(false);

        //connection1.commit();
        Statement st = con3.createStatement();

        st.execute("DROP TABLE T IF EXISTS");
        st.execute("CREATE TABLE T (I INT)");
        st.execute("INSERT INTO T VALUES (2)");

        ResultSet rs = st.executeQuery("SELECT * FROM T");

        rs.next();

        int value = rs.getInt(1);

        con2.commit();
        con3.commit();
        con1.commit();

        rs = st.executeQuery("SELECT * FROM T");

        rs.next();

        if (value != rs.getInt(1)) {
            throw new Exception("value doesn't exist");
        }
    }
 
Example 20
Project: TwitterBoost-Tools   File: DBConn.java   View Source Code Vote up 2 votes
/**
 * @param conn
 * @throws SQLException
 * To Commit and Close the connection
 */
public static void commitAndClose(Connection conn) throws SQLException {
    conn.commit();
    conn.close();
}