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:azkaban.project.JdbcProjectLoader.java

private void cleanOlderProjectVersionFlows(Connection connection, int projectId, int version)
        throws ProjectManagerException {
    final String DELETE_FLOW = "DELETE FROM project_flows WHERE project_id=? AND version<?";
    QueryRunner runner = new QueryRunner();
    try {//w w w. ja  va2  s .  com
        runner.update(connection, DELETE_FLOW, projectId, version);
        connection.commit();
    } catch (SQLException e) {
        throw new ProjectManagerException("Error deleting project version flows " + projectId + ":" + version,
                e);
    }
}

From source file:mupomat.controller.ObradaKorisnik.java

@Override
public Korisnik dodajNovi(Korisnik entitet) {

    try {// w w  w. j av a2s  .  co m
        Connection veza = MySqlBazaPodataka.getConnection();

        veza.setAutoCommit(false);

        PreparedStatement izraz = veza
                .prepareStatement("insert into osoba (oib,ime,prezime,email) values (?,?,?,?)");
        izraz.setString(1, entitet.getOib());
        izraz.setString(2, entitet.getIme());
        izraz.setString(3, entitet.getPrezime());
        izraz.setString(4, entitet.getEmail());
        izraz.executeUpdate();

        izraz = veza.prepareStatement(
                "insert into korisnik (oib,automat,datumregistracije,korisnickoime,lozinka,uloga,aktivan) values (?,?,now(),?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        izraz.setString(1, entitet.getOib());
        izraz.setString(2, entitet.getAutomat());
        izraz.setString(3, entitet.getKorisnickoIme());
        izraz.setString(4, DigestUtils.md5Hex(entitet.getLozinka()));
        izraz.setString(5, entitet.getUloga());
        izraz.setBoolean(6, entitet.isAktivan());
        izraz.executeUpdate();

        ResultSet rs = izraz.getGeneratedKeys();
        rs.next();
        entitet.setSifra(rs.getInt(1));

        izraz.close();
        veza.commit();
        veza.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        return null;
    }

    return entitet;
}

From source file:org.koiroha.jyro.workers.crawler.Crawler.java

/**
 *
 * @param job/* w  ww.j a va  2  s .c o m*/
 * @return
 * @throws WorkerException
*/
@Distribute(name = "crawl", params = { "url", "referer" })
public void crawl(String url, String referer) throws SQLException, JyroException {
    List<URI> urls = retrieveLink(url);
    WorkerContext context = getContext();

    Connection con = Transaction.getConnection();
    con.setAutoCommit(false);

    PreparedStatement stmt1 = con.prepareStatement(
            "INSERT INTO jyro_urls(scheme,host,port,path,retrieved_at,created_at) VALUES(?,?,?,?,?,?)");
    PreparedStatement stmt = con.prepareStatement(
            "SELECT EXISTS(SELECT * FROM jyro_urls WHERE scheme=? AND host=? AND port=? AND path=?)");
    for (URI uri : urls) {
        int port = getPort(uri);
        if (port < 0) {
            logger.debug(uri + " is not supported");
            continue;
        }

        stmt.setString(1, uri.getScheme());
        stmt.setString(2, uri.getHost());
        stmt.setInt(3, port);
        stmt.setString(4, uri.getPath());
        ResultSet rs = stmt.executeQuery();
        rs.next();
        boolean exists = rs.getBoolean(1);
        if (!exists) {
            Timestamp now = new Timestamp(System.currentTimeMillis());
            stmt1.setString(1, uri.getScheme());
            stmt1.setString(2, uri.getHost());
            stmt1.setInt(3, port);
            stmt1.setString(4, uri.getPath());
            stmt1.setTimestamp(5, now);
            stmt1.setTimestamp(6, now);
            stmt1.executeUpdate();
            con.commit();
            context.call("crawl", uri.toString());
        } else {
            logger.info("URL " + uri + " already retrieved");
        }
    }
    stmt.close();
    stmt1.close();
    con.commit();
    return;
}

From source file:com.oic.event.SetProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;/*  w w w.  j a  v  a2  s. c o  m*/
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "UPDATE user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ? "
                + "WHERE userid = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setLong(8, webSocket.getCharacter().getUserId());
        ps.executeUpdate();
        ps.close();

        sql = "UPDATE setting SET privategrade = ?, privatesex = ?, privatebirth =? WHERE userid = ?";
        ps = con.prepareStatement(sql);
        ps.setInt(1, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(2, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vbirthday").toString()));
        ps.setLong(4, webSocket.getCharacter().getUserId());

        ps.executeUpdate();
        ps.close();

        con.commit();

        //TODO 
        responseJSON.put("status", 0);
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }

    webSocket.sendJson(responseJSON);
}

From source file:azkaban.project.JdbcProjectLoader.java

private void cleanOlderProjectVersionProperties(Connection connection, int projectId, int version)
        throws ProjectManagerException {
    final String DELETE_PROPERTIES = "DELETE FROM project_properties WHERE project_id=? AND version<?";
    QueryRunner runner = new QueryRunner();
    try {//www  .j ava2s.c  o m
        runner.update(connection, DELETE_PROPERTIES, projectId, version);
        connection.commit();
    } catch (SQLException e) {
        throw new ProjectManagerException(
                "Error deleting project version properties " + projectId + ":" + version, e);
    }
}

From source file:azkaban.project.JdbcProjectLoader.java

private void cleanOlderProjectFiles(Connection connection, int projectId, int version)
        throws ProjectManagerException {
    final String DELETE_PROJECT_FILES = "DELETE FROM project_files WHERE project_id=? AND version<?";
    QueryRunner runner = new QueryRunner();
    try {/*from  w w w. ja  va 2s  .co m*/
        runner.update(connection, DELETE_PROJECT_FILES, projectId, version);
        connection.commit();
    } catch (SQLException e) {
        throw new ProjectManagerException("Error deleting project version files " + projectId + ":" + version,
                e);
    }
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java

/**
 * Create a ExtendedFieldValue in persistent storage.
 * @param aConnection an open connection to the HarvestDatabase.
 * @param aExtendedFieldValue The ExtendedFieldValue to create in 
 *  persistent storage//w w  w . j  av  a 2 s  .  co  m
 * @param aCommit Should we commit this or not
 * @throws SQLException In case of Database access problems.
 */
public void create(Connection aConnection, ExtendedFieldValue aExtendedFieldValue, boolean aCommit)
        throws SQLException {
    ArgumentNotValid.checkNotNull(aExtendedFieldValue, "aExtendedFieldValue");

    if (aExtendedFieldValue.getExtendedFieldValueID() != null) {
        log.warn("The extendedFieldValueID for this extendedField Value "
                + "is already set. This should probably never happen.");
    } else {
        aExtendedFieldValue.setExtendedFieldValueID(generateNextID(aConnection));
    }

    log.debug("Creating " + aExtendedFieldValue.toString());

    PreparedStatement statement = null;
    aConnection.setAutoCommit(false);
    statement = aConnection.prepareStatement("" + "INSERT INTO extendedfieldvalue "
            + "            (extendedfieldvalue_id, " + "             extendedfield_id, "
            + "             content, " + "             instance_id) " + "VALUES      (?, " + "             ?, "
            + "             ?, " + "             ?) ");

    statement.setLong(1, aExtendedFieldValue.getExtendedFieldValueID());
    statement.setLong(2, aExtendedFieldValue.getExtendedFieldID());
    statement.setString(3, aExtendedFieldValue.getContent());
    statement.setLong(4, aExtendedFieldValue.getInstanceID());

    statement.executeUpdate();
    if (aCommit) {
        aConnection.commit();
    }
}

From source file:com.cloudera.sqoop.manager.SQLServerManagerImportManualTest.java

@Before
public void setUp() {
    super.setUp();

    SqoopOptions options = new SqoopOptions(CONNECT_STRING, TABLE_NAME);
    options.setUsername(DATABASE_USER);//from w w  w . j a  v  a 2  s . co m
    options.setPassword(DATABASE_PASSWORD);

    manager = new SQLServerManager(options);

    // Drop the existing table, if there is one.
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = manager.getConnection();
        stmt = conn.createStatement();
        stmt.execute("DROP TABLE " + TABLE_NAME);
    } catch (SQLException sqlE) {
        LOG.info("Table was not dropped: " + sqlE.getMessage());
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
        } catch (Exception ex) {
            LOG.warn("Exception while closing stmt", ex);
        }
    }

    // Create and populate table
    try {
        conn = manager.getConnection();
        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        // create the database table and populate it with data.
        stmt.executeUpdate(
                "CREATE TABLE " + TABLE_NAME + " (" + "id INT NOT NULL, " + "name VARCHAR(24) NOT NULL, "
                        + "salary FLOAT, " + "dept VARCHAR(32), " + "PRIMARY KEY (id))");

        stmt.executeUpdate(
                "INSERT INTO " + TABLE_NAME + " VALUES(" + "1,'Aaron', " + "1000000.00,'engineering')");
        stmt.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "2,'Bob', " + "400.00,'sales')");
        stmt.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "3,'Fred', 15.00," + "'marketing')");
        conn.commit();
    } catch (SQLException sqlE) {
        LOG.error("Encountered SQL Exception: ", sqlE);
        sqlE.printStackTrace();
        fail("SQLException when running test setUp(): " + sqlE);
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
        } catch (Exception ex) {
            LOG.warn("Exception while closing connection/stmt", ex);
        }
    }
}

From source file:gridool.replication.ReplicationManager.java

public boolean registerReplicaDatabase(@Nonnull Connection conn, String... dbnames) throws SQLException {
    final int dblen = dbnames.length;
    if (dblen < 1) {
        return false;
    }//from  w ww. j  a  va 2  s  .  c  om
    synchronized (lock) {
        int remaining = 0;
        for (int i = 0; i < dblen; i++) {
            final String dbname = dbnames[i];
            if (replicaNameStack.contains(dbname)) {
                dbnames[i] = null;
            } else if (replicaDbMappingCache.containsValue(dbname)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Replica '" + dbname + "' is already mapped");
                }
                dbnames[i] = null;
            } else {
                remaining++;
            }
        }
        if (remaining > 0) {
            //prepareReplicaTable(conn, replicaTableName);
            final Object[][] params = new String[remaining][];
            for (int i = 0; i < dblen; i++) {
                final String dbname = dbnames[i];
                if (dbname != null) {
                    params[i] = new String[] { dbname };
                    replicaNameStack.push(dbname);
                }
            }
            JDBCUtils.batch(conn, "INSERT INTO \"" + replicaTableName + "\"(dbname) values(?)", params);
            conn.commit();
        }
        return true;
    }
}

From source file:azkaban.project.JdbcProjectLoader.java

private void cleanOlderProjectVersion(Connection connection, int projectId, int version)
        throws ProjectManagerException {
    final String UPDATE_PROJECT_VERSIONS = "UPDATE project_versions SET num_chunks=0 WHERE project_id=? AND version<?";
    QueryRunner runner = new QueryRunner();
    try {//from  ww  w .j a v a2s.co m
        runner.update(connection, UPDATE_PROJECT_VERSIONS, projectId, version);
        connection.commit();
    } catch (SQLException e) {
        throw new ProjectManagerException(
                "Error updating project version chunksize " + projectId + ":" + version, e);
    }
}