Example usage for java.sql Connection getAutoCommit

List of usage examples for java.sql Connection getAutoCommit

Introduction

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

Prototype

boolean getAutoCommit() throws SQLException;

Source Link

Document

Retrieves the current auto-commit mode for this Connection object.

Usage

From source file:org.efaps.db.databases.PostgreSQLDatabase.java

/**
 * <p>Creates sequence <code>_name</code> in PostgreSQL. As name of the
 * sequence the lower case of <code>_name</code> is used.</p>
 * <p>The minimum and starting value is set to <code>_startValue</code>
 * minus one and then updated to current value (by fetching a value from
 * the sequence). The current value is <code>_startValue</code> minus one
 * so that a call to {@link #nextSequence(Connection, String)} returns the
 * expected <code>_startValue</code>.</p>
 *
 * @param _con          SQL connection// w  ww . j a v  a  2 s. com
 * @param _name         name of the sequence to update
 * @param _startValue   start value of the sequence
 * @return this database instance
 * @throws SQLException if sequence could not be created
 * @see #nextSequence(Connection, String)
 */
@Override
public PostgreSQLDatabase createSequence(final Connection _con, final String _name, final long _startValue)
        throws SQLException {
    final long value = _startValue - 1;
    final StringBuilder cmd = new StringBuilder();
    cmd.append("CREATE SEQUENCE \"").append(_name.toLowerCase()).append("\" INCREMENT 1").append(" MINVALUE  ")
            .append(value).append(" MAXVALUE 9223372036854775807 ").append(" START ").append(value)
            .append(" CACHE 1;");

    final PreparedStatement stmt = _con.prepareStatement(cmd.toString());
    try {
        stmt.execute();
    } finally {
        stmt.close();
    }
    if (!_con.getAutoCommit()) {
        _con.commit();
    }

    nextSequence(_con, _name);
    return this;
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseHandler.java

/**
 * To update the databse when a dashboard is deleted
 *
 * @param tenantId    Id of the tenant which the dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @throws DashboardPortalException/*  ww w.  j  av  a 2 s . co m*/
 */
public void updateAfterDeletingDashboard(int tenantId, String dashboardId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = dataBaseInitializer.getDBConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_DELETE_DASHBOARD_OPERATION);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        preparedStatement.executeUpdate();
        if (!dashboardId.contains("$")) {
            preparedStatement = connection
                    .prepareStatement(DataSourceConstants.SQL_DELETE_ALL_DASHBOARD_OPERATION);
            preparedStatement.setInt(1, tenantId);
            preparedStatement.setString(2, dashboardId + "$%");
            preparedStatement.executeUpdate();
        }
        if (!connection.getAutoCommit()) {
            connection.commit();
        }

    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * This is used to insert a gadget usage info
 *
 * @param tenantID    Tenant ID of the tenant which the dashboard belongs to
 * @param dashboardID Dashboard ID of the dashboard
 * @param gadgetId    Gadget ID that is used in the dashboard
 * @param gadgetState State of the gadget whether it is exist or not
 * @param usageData   Representation of the usage info of the particular gadget in the dashboard
 * @throws DashboardPortalException//from   w w  w.j  a va 2  s . c om
 */
public void insertGadgetUsageInfo(int tenantID, String dashboardID, String gadgetId, String gadgetState,
        String usageData) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_INSERT_USAGE_OPERATION);
        preparedStatement.setInt(1, tenantID);
        preparedStatement.setString(2, dashboardID);
        preparedStatement.setString(3, gadgetId);
        preparedStatement.setString(4, gadgetState);
        preparedStatement.setString(5, usageData);
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To update the record on a gadget usage
 *
 * @param tenantID    ID of the tenant which the dashboard belongs to
 * @param dashboardID ID of the dashboard
 * @param gadgetId    ID of the gadget/*from  w  w  w  .  j a v  a 2 s  . c  o  m*/
 * @param gadgetState State of the gadget whether it is deleted or not
 * @param usageData   Usage information of the gadget
 * @throws DashboardPortalException
 */
public void updateGadgetUsageInfo(int tenantID, String dashboardID, String gadgetId, String gadgetState,
        String usageData) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_UPDATE_USAGE_OPERATION);
        preparedStatement.setString(1, gadgetState);
        preparedStatement.setString(2, usageData);
        preparedStatement.setInt(3, tenantID);
        preparedStatement.setString(4, dashboardID);
        preparedStatement.setString(5, gadgetId);
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
}

From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java

public Map find(String type, String query, Map parameters) throws WGQueryException {

    if (type == null || type.equals("native")) {
        type = "sql";
    }/*from   w w w . j ava  2s  .  c  om*/

    List nativeOptions = new ArrayList();
    String nativeOptionsString = (String) parameters.get(WGDatabase.QUERYOPTION_NATIVEOPTIONS);
    if (nativeOptionsString != null) {
        nativeOptions.addAll(WGUtils.deserializeCollection(nativeOptionsString.toLowerCase(), ",", true));
    }

    ResultSet resultSet = null;
    String table = null;
    PreparedStatement stmt;
    Boolean resetAutocommit = null;
    Connection connection = null;
    try {

        // Create statement
        connection = getConnection();
        boolean isUpdate = nativeOptions.contains("update");
        if (isUpdate && !connection.getAutoCommit()) {
            resetAutocommit = connection.getAutoCommit();
            connection.setAutoCommit(true);
        }

        if (type.equals("sql")) {

            stmt = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,
                    (isUpdate ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY));

        } else if (type.startsWith("table:")) {

            table = type.substring(6).trim();
            if (!_tables.keySet().contains(table.toLowerCase())) {
                throw new WGQueryException(query, "Table '" + table + "' does not exist or has no primary key");
            }

            if (query != null && !query.trim().equals("")) {
                query = "SELECT * FROM " + table + " WHERE " + query;
            } else {
                query = "SELECT * FROM " + table;
            }
            stmt = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

        } else {
            throw new WGQueryException(query, "Unknown query type: " + type);
        }

        // Apply parameters
        if (parameters.containsKey(WGDatabase.QUERYOPTION_MAXRESULTS)) {
            stmt.setMaxRows(((Number) parameters.get(WGDatabase.QUERYOPTION_MAXRESULTS)).intValue());
        }

        applyQueryParameters(parameters, stmt, query);

        // Execute and extract data
        stmt.execute();
        resultSet = stmt.getResultSet();
        Map results;
        if (resultSet != null) {
            results = extractRowResults(resultSet, table);
        } else {
            results = new HashMap();
        }

        return results;

    } catch (SQLException e) {
        throw new WGQueryException(query, e.getMessage(), e);
    } finally {
        if (connection != null && resetAutocommit != null) {
            try {
                connection.setAutoCommit(resetAutocommit);
            } catch (SQLException e) {
                throw new WGQueryException(query, "Exception resetting autocommit", e);
            }
        }
        closeResultSet(resultSet);
    }
}

From source file:org.alinous.plugin.derby.DerbyDataSource.java

public boolean begin(Object connectionHandle, int transactionIsolationLevel) throws DataSourceException {
    Connection con = (Connection) connectionHandle;
    boolean autoCommit;

    try {/*from   w w w .ja  v  a 2  s .c  om*/
        autoCommit = con.getAutoCommit();
    } catch (SQLException e) {
        throw new DataSourceException(e);
    }

    try {
        con.setAutoCommit(false);
    } catch (SQLException e) {
        throw new DataSourceException(e);
    }

    Statement batchStmt = null;
    try {
        batchStmt = con.createStatement();
        this.batchedStatementMap.put(con, batchStmt);
    } catch (SQLException e) {
        throw new DataSourceException(e);
    }

    return autoCommit;
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To get the details of the defective usage data
 *
 * @param tenantId    Id of the tenant which dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @return Array list of usage data which has the deleted gadgets
 * @throws DashboardPortalException/*from  ww w  .  j av  a2 s  .c  om*/
 */
public List<String> getDefectiveUsageData(int tenantId, String dashboardId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    List<String> defectiveUsageData = new ArrayList<String>();
    String deletedGadgetState = "DELETED";
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_CHECK_DEFECTIVE_DASHBOARD);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        preparedStatement.setString(3, deletedGadgetState);
        resultSet = preparedStatement.executeQuery();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        while (resultSet.next()) {
            defectiveUsageData.add(resultSet.getString("USAGE_DATA"));
        }
    } catch (SQLException e) {
        log.error("Cannot check defective dashboard ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, resultSet);
    }
    return defectiveUsageData;
}

From source file:org.alinous.plugin.mysql.MySQLDataSource.java

public boolean begin(Object connectionHandle, int transactionIsolationLevel) throws DataSourceException {
    Connection con = (Connection) connectionHandle;
    boolean autoCommit;

    try {//from  ww w . ja  va 2  s. c  o  m
        autoCommit = con.getAutoCommit();
    } catch (SQLException e) {
        throw new DataSourceException(e);
    }

    try {
        con.setAutoCommit(false);
    } catch (SQLException e) {
        throw new DataSourceException(e);
    }

    /*
    Statement batchStmt = null;
    try {
       batchStmt = con.createStatement();
       this.batchedStatementMap.put(con, batchStmt);
    } catch (SQLException e) {
       throw new DataSourceException(e);
    }
    */
    return autoCommit;
}

From source file:org.alinous.plugin.derby.DerbyDataSource.java

public void storeBinary(Object connectionHandle, InputStream stream, int length, String table,
        String blobColumn, WhereClause where, PostContext context, VariableRepository provider)
        throws ExecutionException {
    UpdateSentence sentence = new UpdateSentence();
    sentence.setTable(new TableIdentifier(table));
    TypeHelper helper = this.typeHelper.newHelper(false, sentence);

    StringBuffer buff = new StringBuffer();

    buff.append("UPDATE ");
    buff.append(table);//w ww  .j a va 2 s  . c o m
    buff.append(" SET ");
    buff.append(blobColumn);
    buff.append("=?");

    if (where != null && where.isReady(context, provider, null)) {
        buff.append(" ");
        buff.append(where.extract(context, provider, null, null, helper));
    }

    Connection con = (Connection) connectionHandle;
    boolean lastAutoCommit = false;
    try {
        lastAutoCommit = con.getAutoCommit();
        if (lastAutoCommit == true) {
            con.setAutoCommit(false);
        }

        PreparedStatement statement = con.prepareStatement(buff.toString());
        statement.setBinaryStream(1, stream, length);
        statement.executeUpdate();

        //con.commit();
    } catch (SQLException e) {
        throw new ExecutionException(e, "Failed in storing blob"); // i18n
    } finally {
        try {
            if (lastAutoCommit == true) {
                con.setAutoCommit(lastAutoCommit);
            }
        } catch (SQLException e) {
        }
    }
    // UPDATE table SET blobColumn = ? WHERE...

}

From source file:net.sf.jabref.sql.exporter.DBExporter.java

/**
 * Accepts the BibDatabase and MetaData, generates the DML required to create and populate SQL database tables,
 * and writes this DML to the specified SQL database.
 *
 * @param database        The BibDatabase to export
 * @param metaData        The MetaData object containing the groups information
 * @param keySet          The set of IDs of the entries to export.
 * @param databaseStrings The necessary database connection information
 *//*www .  j a v a2s.c o  m*/
public void exportDatabaseToDBMS(final BibDatabase database, final MetaData metaData, Set<String> keySet,
        DBStrings databaseStrings, JabRefFrame frame) throws Exception {
    String dbName;
    Connection conn = null;
    boolean redisplay = false;
    try {
        conn = this.connectToDB(databaseStrings);
        createTables(conn);
        Vector<Vector<String>> matrix = createExistentDBNamesMatrix(databaseStrings);
        DBImportExportDialog dialogo = new DBImportExportDialog(frame, matrix,
                DBImportExportDialog.DialogType.EXPORTER);
        if (dialogo.removeAction) {
            dbName = getDBName(matrix, databaseStrings, frame, dialogo);
            removeDB(dialogo, dbName, conn, metaData);
            redisplay = true;
        } else if (dialogo.hasDBSelected) {
            dbName = getDBName(matrix, databaseStrings, frame, dialogo);
            performExport(database, metaData, keySet, conn, dbName);
        }
        if (!conn.getAutoCommit()) {
            conn.commit();
            conn.setAutoCommit(true);
        }
        if (redisplay) {
            exportDatabaseToDBMS(database, metaData, keySet, databaseStrings, frame);
        }
    } catch (SQLException ex) {
        if ((conn != null) && !conn.getAutoCommit()) {
            conn.rollback();
        }
        throw ex;
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
}