Example usage for java.sql Connection commit

List of usage examples for java.sql Connection commit

Introduction

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

Prototype

void commit() throws SQLException;

Source Link

Document

Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.

Usage

From source file:net.noday.core.dao.AppDao.java

public App getAppConfig() {
    List<String> tables = jdbc.queryForList("show tables", String.class);
    Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource());
    try {/*from   www.  jav a  2  s  .  co m*/
        conn.setAutoCommit(false);
        if (tables == null || tables.size() == 0 || !tables.contains("app_config")) {
            initDB();
        } else {
            String version = jdbc.queryForObject("select a.version from app_config a limit 1", String.class);
            if (!"1.1".equalsIgnoreCase(version)) {
                updateDB("1_1");
            }
        }
        conn.commit();
    } catch (DataAccessException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    String sql = "select * from app_config limit 1";
    App cfg = jdbc.queryForObject(sql, new BeanPropertyRowMapper<App>(App.class));
    if (cfg == null) {
        throw new AppStartupException("??");
    }
    return cfg;
}

From source file:com.cloudera.sqoop.orm.TestClassWriter.java

@Test
public void testWeirdColumnNames() throws SQLException {
    // Recreate the table with column names that aren't legal Java identifiers.
    String tableName = HsqldbTestServer.getTableName();
    Connection connection = testServer.getConnection();
    Statement st = connection.createStatement();
    try {//from w w w .  j a v a2  s .co m
        st.executeUpdate("DROP TABLE " + tableName + " IF EXISTS");
        st.executeUpdate("CREATE TABLE " + tableName + " (class INT, \"9field\" INT)");
        st.executeUpdate("INSERT INTO " + tableName + " VALUES(42, 41)");
        connection.commit();
    } finally {
        st.close();
        connection.close();
    }

    String[] argv = { "--bindir", JAR_GEN_DIR, "--outdir", CODE_GEN_DIR, "--package-name",
            OVERRIDE_PACKAGE_NAME, };

    runGenerationTest(argv, OVERRIDE_PACKAGE_NAME + "." + HsqldbTestServer.getTableName());
}

From source file:com.wso2telco.refund.utils.DbUtils.java

/**
 * Disconnect.//  ww  w  . j ava  2s. c  om
 *
 * @param con the con
 * @throws Exception the exception
 */
public void disconnect(Connection con) throws Exception {
    System.out.println();
    //System.out.println("  Disconnect from database.");

    // makes all changes made since the previous commit/rollback permanent
    // and releases any database locks currrently held by the Connection.
    con.commit();

    // immediately disconnects from database and releases JDBC resources
    con.close();
}

From source file:com.stratio.ingestion.sink.jdbc.JDBCSinkTest.java

@Test
public void mappedWithH2() throws Exception {
    Class.forName("org.h2.Driver").newInstance();
    Connection conn = DriverManager.getConnection("jdbc:h2:/tmp/jdbcsink_test");
    conn.prepareStatement("DROP TABLE public.test IF EXISTS;").execute();
    conn.prepareStatement(/*from w w  w .j a  v a 2 s .  com*/
            "CREATE TABLE public.test (myInteger INTEGER, myString VARCHAR, myId BIGINT AUTO_INCREMENT PRIMARY KEY);")
            .execute();
    conn.commit();
    conn.close();

    Context ctx = new Context();
    ctx.put("driver", "org.h2.Driver");
    ctx.put("connectionString", "jdbc:h2:/tmp/jdbcsink_test");
    ctx.put("table", "test");
    ctx.put("sqlDialect", "H2");
    ctx.put("batchSize", "1");

    JDBCSink jdbcSink = new JDBCSink();

    Configurables.configure(jdbcSink, ctx);

    Context channelContext = new Context();
    channelContext.put("capacity", "10000");
    channelContext.put("transactionCapacity", "200");

    Channel channel = new MemoryChannel();
    channel.setName("junitChannel");
    Configurables.configure(channel, channelContext);

    jdbcSink.setChannel(channel);

    channel.start();
    jdbcSink.start();

    Transaction tx = channel.getTransaction();
    tx.begin();

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar"); // Overwrites the value defined in JSON body
    headers.put("myInteger", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Date myDate = new Date();
    headers.put("myDate", Long.toString(myDate.getTime()));

    headers.put("myString2", "baz");

    Event event = EventBuilder.withBody(new byte[0], headers);
    channel.put(event);

    tx.commit();
    tx.close();

    jdbcSink.process();

    jdbcSink.stop();
    channel.stop();

    conn = DriverManager.getConnection("jdbc:h2:/tmp/jdbcsink_test");
    ResultSet resultSet = conn.prepareStatement("SELECT * FROM public.test").executeQuery();
    resultSet.next();
    assertThat(resultSet.getInt("myInteger")).isEqualTo(64);
    assertThat(resultSet.getString("myString")).isEqualTo("bar");
    conn.close();
}

From source file:com.glaf.core.execution.FileExecutionHelper.java

public void createTable(Connection connection) {
    boolean autoCommit = false;
    try {/*from www  . j  a  v  a2  s .  c  om*/
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        TableDefinition tableDefinition = BlobItemDomainFactory.getTableDefinition();
        if (!DBUtils.tableExists(connection, BlobItemDomainFactory.TABLENAME)) {
            DBUtils.createTable(connection, tableDefinition);
        } else {
            DBUtils.alterTable(connection, tableDefinition);
        }
        connection.commit();
        connection.setAutoCommit(autoCommit);
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:com.krawler.esp.servlets.FileImporterServlet.java

public static void fildoc(String docid, String docname, String projid, String svnName, String userid, long size)
        throws ServiceException {

    PreparedStatement pstmt = null;
    String sql = null;//  w w  w.j av a 2s  . c o m
    Connection conn = null;
    try {
        conn = DbPool.getConnection();
        java.util.Date d = new java.util.Date();
        java.sql.Timestamp docdatemod = new Timestamp(d.getTime());
        String currentStoreIndex = StorageHandler.GetCurrentStorageIndex();
        sql = "INSERT INTO docs(docid, docname, docdatemod, "
                + "userid,svnname,storageindex,docsize) VALUES (?,?,?,?,?,?,?)";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, docid);
        pstmt.setString(2, docname);
        pstmt.setObject(3, docdatemod);
        pstmt.setObject(4, userid);
        pstmt.setString(5, svnName);
        pstmt.setString(6, currentStoreIndex);
        pstmt.setObject(7, size);
        pstmt.executeUpdate();
        sql = "insert into docprerel (docid,userid,permission) values(?,?,?)";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, docid);
        pstmt.setString(2, projid);
        pstmt.setObject(3, "8");
        pstmt.executeUpdate();

        conn.commit();
    } catch (ServiceException ex) {
        DbPool.quietRollback(conn);
        throw ServiceException.FAILURE("FileImporterServlet.fildoc", ex);
    } catch (Exception ex) {
        DbPool.quietRollback(conn);
        throw ServiceException.FAILURE("FileImporterServlet.fildoc", ex);
    } finally {
        DbPool.quietClose(conn);
    }
}

From source file:com.fileanalyzer.dao.impl.FileStatisticDAOImpl.java

@Override
public Long getMaxId() {
    Connection con = null;
    PreparedStatement statement = null;
    String sql = "select max(id) from " + FileStatistic.FileStatisticKey.TABLE;
    Long maxId = null;/*from w  w  w.  j  a  v  a 2  s .co  m*/
    try {
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        statement = con.prepareStatement(sql);
        ResultSet rs = statement.executeQuery();
        if (rs.next())
            maxId = rs.getLong(1);
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, statement);
    }
    return maxId;
}

From source file:com.stratio.ingestion.sink.jdbc.JDBCSinkTest.java

@Test
public void templateWithH2() throws Exception {
    Class.forName("org.h2.Driver").newInstance();
    Connection conn = DriverManager.getConnection("jdbc:h2:/tmp/jdbcsink_test");
    conn.prepareStatement("DROP TABLE public.test IF EXISTS;").execute();
    conn.prepareStatement(//from   w  ww  . jav a2 s  .com
            "CREATE TABLE public.test (myInteger INTEGER, myString VARCHAR, myId BIGINT AUTO_INCREMENT PRIMARY KEY);")
            .execute();
    conn.commit();
    conn.close();

    Context ctx = new Context();
    ctx.put("driver", "org.h2.Driver");
    ctx.put("connectionString", "jdbc:h2:/tmp/jdbcsink_test");
    ctx.put("sqlDialect", "H2");
    ctx.put("batchSize", "1");
    ctx.put("sql",
            "INSERT INTO \"PUBLIC\".\"TEST\" (\"MYINTEGER\", \"MYSTRING\") VALUES (cast(${header.myInteger:int} as integer), cast(${header.myString:varchar} as varchar))");

    JDBCSink jdbcSink = new JDBCSink();

    Configurables.configure(jdbcSink, ctx);

    Context channelContext = new Context();
    channelContext.put("capacity", "10000");
    channelContext.put("transactionCapacity", "200");

    Channel channel = new MemoryChannel();
    channel.setName("junitChannel");
    Configurables.configure(channel, channelContext);

    jdbcSink.setChannel(channel);

    channel.start();
    jdbcSink.start();

    Transaction tx = channel.getTransaction();
    tx.begin();

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar"); // Overwrites the value defined in JSON body
    headers.put("myInteger", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Date myDate = new Date();
    headers.put("myDate", Long.toString(myDate.getTime()));

    headers.put("myString2", "baz");

    Event event = EventBuilder.withBody(new byte[0], headers);
    channel.put(event);

    tx.commit();
    tx.close();

    jdbcSink.process();

    jdbcSink.stop();
    channel.stop();

    conn = DriverManager.getConnection("jdbc:h2:/tmp/jdbcsink_test");

    ResultSet rs = conn.prepareStatement("SELECT count(*) AS count FROM public.test").executeQuery();
    rs.next();
    assertThat(rs.getInt("count")).isEqualTo(1);

    rs = conn.prepareStatement("SELECT * FROM public.test").executeQuery();
    rs.next();
    for (int i = 1; i <= 3; i++) {
        System.out.println(rs.getString(i));
    }
    assertThat(rs.getInt("myInteger")).isEqualTo(64);
    assertThat(rs.getString("myString")).isEqualTo("bar");
    conn.close();

}

From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java

@Override
public List<Files> getAll() {
    Connection con = null;
    PreparedStatement statement = null;
    String sql = "select * from " + Files.FilesFieldsKey.TABLE;
    List<Files> listFStat = new ArrayList<>();
    try {// w ww  .  jav  a 2  s  .c o  m
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        statement = con.prepareStatement(sql);
        ResultSet rs = statement.executeQuery();
        ResultSetToListFiles(rs, listFStat);
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, statement);
    }
    return listFStat;
}

From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java

@Override
public Long getMaxId() {
    Connection con = null;
    PreparedStatement statement = null;
    String sql = "select max(id) from " + Files.FilesFieldsKey.TABLE;
    Long maxId = null;//from w  w w  . ja v  a 2s .  c  om
    try {
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        statement = con.prepareStatement(sql);
        ResultSet rs = statement.executeQuery();
        if (rs.next())
            maxId = rs.getLong(1);
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, statement);
    }
    return maxId;
}