List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:org.intermine.modelproduction.MetadataManager.java
/** * Store a binary (key, value) pair in the metadata table of the database * @param database the database/*from www .ja v a2 s .c om*/ * @param key the key * @param value the byte array of the value * @throws SQLException if an error occurs */ public static void storeBinary(Database database, String key, byte[] value) throws SQLException { Connection connection = database.getConnection(); boolean autoCommit = connection.getAutoCommit(); try { connection.setAutoCommit(false); ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM " + METADATA_TABLE); ResultSetMetaData meta = rs.getMetaData(); if (meta.getColumnCount() != 3) { connection.createStatement().execute("ALTER TABLE " + METADATA_TABLE + " ADD blob_value BYTEA"); } connection.createStatement().execute("DELETE FROM " + METADATA_TABLE + " where key = '" + key + "'"); PreparedStatement pstmt = connection.prepareStatement( "INSERT INTO " + METADATA_TABLE + " (key, blob_value) " + "VALUES('" + key + "', ?)"); pstmt.setBytes(1, value); pstmt.executeUpdate(); connection.commit(); pstmt.close(); } finally { connection.setAutoCommit(autoCommit); connection.close(); } }
From source file:org.intermine.sql.DatabaseUtil.java
/** * Grant permission on all tables for given user on specified database. * @param db the database to grant permissions on * @param user the username to grant permission to * @param perm permission to grant/*from ww w . j a va 2 s . com*/ * @throws SQLException if db problem */ public static void grant(Database db, String user, String perm) throws SQLException { Connection conn = db.getConnection(); boolean autoCommit = conn.getAutoCommit(); try { conn.setAutoCommit(true); Statement s = conn.createStatement(); ResultSet res = conn.getMetaData().getTables(null, null, null, null); while (res.next()) { if ("TABLE".equals(res.getString(4))) { String sql = "GRANT " + perm + " ON " + res.getString(3) + " TO " + user; LOG.debug(sql); s.execute(sql); } } conn.setAutoCommit(autoCommit); } finally { conn.setAutoCommit(autoCommit); conn.close(); } }
From source file:org.diffkit.util.DKSqlUtil.java
/** * null and Exception safe/*w w w . j av a2s.c o m*/ */ public static boolean executeUpdate(String sql_, Connection connection_) { LOG.debug("sql_->{}", sql_); if ((sql_ == null) || (connection_ == null)) return false; Statement statement = createStatement(connection_); if (statement == null) return false; try { statement.execute(sql_); if (!connection_.getAutoCommit()) connection_.commit(); return true; } catch (Exception e_) { LOG.error(null, e_); return false; } }
From source file:org.intermine.sql.DatabaseUtil.java
/** * Analyse database table for a given class and all associated indirection tables. * WARNING: currently PostgreSQL specific * @param db the database to analyse//from www . j a v a 2 s . co m * @param cld description of class to analyse * @param full if true perform VACUUM FULL ANALYSE * @throws SQLException if db problem */ public static void analyse(Database db, ClassDescriptor cld, boolean full) throws SQLException { Set<String> tables = new HashSet<String>(); tables.add(getTableName(cld)); tables.addAll(getIndirectionTableNames(cld)); Connection conn = db.getConnection(); boolean autoCommit = conn.getAutoCommit(); try { conn.setAutoCommit(true); Statement s = conn.createStatement(); for (String table : tables) { if (full) { String sql = "VACUUM FULL ANALYSE " + table; LOG.info(sql); s.execute(sql); } else { String sql = "ANALYSE " + table; LOG.info(sql); s.execute(sql); } } conn.setAutoCommit(autoCommit); } finally { conn.setAutoCommit(autoCommit); conn.close(); } }
From source file:com.zimbra.cs.db.DbPool.java
public static DbConnection getConnection(Mailbox mbox) throws ServiceException { if (!isInitialized()) { throw ServiceException.FAILURE("Database connection pool not initialized.", null); }/*from w w w . j a v a2 s . c o m*/ Integer mboxId = mbox != null ? mbox.getId() : -1; //-1 == zimbra db and/or initialization where mbox isn't known yet try { Db.getInstance().preOpen(mboxId); long start = ZimbraPerf.STOPWATCH_DB_CONN.start(); // If the connection pool is overutilized, warn about potential leaks PoolingDataSource pool = getPool(); checkPoolUsage(); Connection dbconn = null; DbConnection conn = null; try { dbconn = pool.getConnection(); if (dbconn.getAutoCommit() != false) dbconn.setAutoCommit(false); // We want READ COMMITTED transaction isolation level for duplicate // handling code in BucketBlobStore.newBlobInfo(). if (Db.supports(Db.Capability.READ_COMMITTED_ISOLATION)) dbconn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); conn = new DbConnection(dbconn, mboxId); Db.getInstance().postOpen(conn); } catch (SQLException e) { try { if (dbconn != null && !dbconn.isClosed()) dbconn.close(); } catch (SQLException e2) { ZimbraLog.sqltrace.warn("DB connection close caught exception", e); } throw ServiceException.FAILURE("getting database connection", e); } // If we're debugging, update the counter with the current stack trace if (ZimbraLog.dbconn.isDebugEnabled()) { Throwable t = new Throwable(); conn.setStackTrace(t); String stackTrace = SystemUtil.getStackTrace(t); synchronized (sConnectionStackCounter) { sConnectionStackCounter.increment(stackTrace); } } if (mbox != null) Db.registerDatabaseInterest(conn, mbox); ZimbraPerf.STOPWATCH_DB_CONN.stop(start); return conn; } catch (ServiceException se) { //if connection open fails unlock Db.getInstance().abortOpen(mboxId); throw se; } }
From source file:com.concursive.connect.web.modules.common.social.rating.dao.Rating.java
/** * Deletes just a specific user's rating, and updates the parent table with a proper calculation * * @param db//from w w w . j a v a 2 s. c o m * @param userId * @param objectId * @param table * @param uniqueField * @throws SQLException */ public static synchronized void delete(Connection db, int userId, int objectId, String table, String uniqueField) throws SQLException { boolean commit = false; try { commit = db.getAutoCommit(); if (commit) { db.setAutoCommit(false); } // Get the project's rating int ratingCount = queryObjectRatingCount(db, objectId, table, uniqueField); // Get the user's rating int thisRating = queryUserRating(db, userId, objectId, table, uniqueField); // Delete the user's rating PreparedStatement pst = db.prepareStatement( "DELETE FROM " + table + "_rating " + "WHERE " + uniqueField + " = ? " + "AND enteredby = ? "); pst.setInt(1, objectId); pst.setInt(2, userId); int deleteCount = pst.executeUpdate(); pst.close(); if (deleteCount > 0 && thisRating != INAPPROPRIATE_COMMENT) { // Update the parent table's rating information // NOTE: make sure not to divide by 0 pst = db.prepareStatement("UPDATE " + table + " " + "SET rating_count = rating_count - ?, rating_value = rating_value - ?, " + (ratingCount == 0 ? "rating_avg = 0 " : "rating_avg = ((rating_value - ?) / (rating_count - ?)) ") + "WHERE " + uniqueField + " = ? "); int i = 0; pst.setInt(++i, 1); pst.setInt(++i, thisRating); if (ratingCount > 1) { pst.setInt(++i, thisRating); pst.setInt(++i, 1); } pst.execute(); pst.close(); } } catch (Exception e) { if (commit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } }
From source file:org.flowable.form.engine.impl.db.FormDbSchemaManager.java
protected static Liquibase createLiquibaseInstance() { try {/*from ww w . j a va 2s .com*/ Connection jdbcConnection = null; CommandContext commandContext = CommandContextUtil.getCommandContext(); FormEngineConfiguration formEngineConfiguration = CommandContextUtil .getFormEngineConfiguration(commandContext); if (commandContext == null) { jdbcConnection = CommandContextUtil.getFormEngineConfiguration(commandContext).getDataSource() .getConnection(); } else { jdbcConnection = CommandContextUtil.getDbSqlSession(commandContext).getSqlSession().getConnection(); } if (!jdbcConnection.getAutoCommit()) { jdbcConnection.commit(); } DatabaseConnection connection = new JdbcConnection(jdbcConnection); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection); database.setDatabaseChangeLogTableName( FormEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName()); database.setDatabaseChangeLogLockTableName(FormEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName()); if (StringUtils.isNotEmpty(formEngineConfiguration.getDatabaseSchema())) { database.setDefaultSchemaName(formEngineConfiguration.getDatabaseSchema()); database.setLiquibaseSchemaName(formEngineConfiguration.getDatabaseSchema()); } if (StringUtils.isNotEmpty(formEngineConfiguration.getDatabaseCatalog())) { database.setDefaultCatalogName(formEngineConfiguration.getDatabaseCatalog()); database.setLiquibaseCatalogName(formEngineConfiguration.getDatabaseCatalog()); } Liquibase liquibase = new Liquibase(LIQUIBASE_CHANGELOG, new ClassLoaderResourceAccessor(), database); return liquibase; } catch (Exception e) { throw new FlowableException("Error creating liquibase instance", e); } }
From source file:com.stratelia.webactiv.util.DBUtil.java
public static void rollback(Connection connection) { if (connection != null) { try {/* ww w .j av a 2 s. c om*/ if (!connection.getAutoCommit() && !connection.isClosed()) { connection.rollback(); } } catch (SQLException e) { SilverTrace.error("util", "DBUtil.close", "util.CAN_T_ROLLBACK_CONNECTION", e); } } }
From source file:com.concursive.connect.web.modules.login.utils.UserUtils.java
/** * Creates a user's profile and sets the id on the user object * * @param db// w w w . j a v a2 s.c o m * @param user * @param prefs * @throws SQLException */ public static void addUserProfile(Connection db, User user, ApplicationPrefs prefs) throws SQLException { boolean autoCommit = db.getAutoCommit(); try { if (autoCommit) { db.setAutoCommit(false); } // Determine the project features ProjectFeatures features = new ProjectFeatures(); ArrayList<String> modules = new ArrayList<String>(); modules.add("Profile"); String enabledModules = prefs.get(ApplicationPrefs.DEFAULT_USER_PROFILE_TABS); // if (enabledModules == null || enabledModules.contains("Reviews")) { // modules.add("Reviews"); // } if (enabledModules == null || enabledModules.contains("Blog")) { modules.add("News=My Blog"); } if (enabledModules == null || enabledModules.contains("Wiki")) { modules.add("Wiki=About Me"); } if (enabledModules == null || enabledModules.contains("Classifieds")) { modules.add("My Classifieds"); } if (enabledModules == null || enabledModules.contains("Documents")) { modules.add("Documents=My Documents"); } if (enabledModules == null || enabledModules.contains("Lists")) { modules.add("My Lists"); } if (enabledModules == null || enabledModules.contains("Badges")) { modules.add("My Badges"); } if (enabledModules == null || enabledModules.contains("Friends")) { modules.add("Team=Friends"); } if (enabledModules == null || enabledModules.contains("Messages")) { modules.add("Messages"); } int count = 0; for (String modulePreference : modules) { String moduleName = null; String moduleLabel = null; if (modulePreference.indexOf("=") != -1) { moduleName = modulePreference.split("=")[0]; moduleLabel = modulePreference.split("=")[1]; } else { moduleName = modulePreference; moduleLabel = modulePreference; } ObjectUtils.setParam(features, "order" + moduleName, count + 1); ObjectUtils.setParam(features, "label" + moduleName, moduleLabel); ObjectUtils.setParam(features, "show" + moduleName, true); } // Determine the category id ProjectCategoryList projectCategoryList = new ProjectCategoryList(); projectCategoryList.setCategoryDescription("People"); projectCategoryList.buildList(db); ProjectCategory people = projectCategoryList.getFromValue("People"); // Create a user project profile Project project = new Project(); project.setInstanceId(user.getInstanceId()); project.setGroupId(1); project.setApproved(user.getEnabled()); project.setProfile(true); project.setCategoryId(people.getId()); project.setOwner(user.getId()); project.setEnteredBy(user.getId()); project.setModifiedBy(user.getId()); // Determine how to record the user's name in the profile if ("true".equals(prefs.get(ApplicationPrefs.USERS_ARE_ANONYMOUS))) { project.setTitle(user.getNameFirstLastInitial()); } else { project.setTitle(user.getNameFirstLast()); } project.setKeywords(user.getNameFirstLast()); project.setShortDescription("My Profile"); project.setCity(user.getCity()); project.setState(user.getState()); project.setCountry(user.getCountry()); project.setPostalCode(user.getPostalCode()); project.setFeatures(features); // Access rules will allow this profile to be searched and seen project.getFeatures().setUpdateAllowGuests(true); project.getFeatures().setAllowGuests(true); if ("true".equals(prefs.get(ApplicationPrefs.INFORMATION_IS_SENSITIVE))) { project.getFeatures().setAllowGuests(false); } // A join request can be made which requires approval by the profile owner project.getFeatures().setUpdateAllowParticipants(true); project.getFeatures().setAllowParticipants(true); // Anyone can see the profile page project.getFeatures().setUpdateMembershipRequired(true); project.getFeatures().setMembershipRequired(true); project.insert(db); project.getFeatures().setId(project.getId()); project.getFeatures().update(db); updateProfileProjectId(db, user, project); // Determine which role level the user is for their own profile LookupList roleList = CacheUtils.getLookupList("lookup_project_role"); int defaultUserLevel = roleList.getIdFromLevel(TeamMember.MANAGER); if (!user.getAccessAdmin() && prefs.has(ApplicationPrefs.DEFAULT_USER_PROFILE_ROLE)) { int userLevelPreference = roleList .getIdFromValue(prefs.get(ApplicationPrefs.DEFAULT_USER_PROFILE_ROLE)); if (userLevelPreference > -1) { defaultUserLevel = userLevelPreference; } } // Add the user as a member of the profile TeamMember member = new TeamMember(); member.setUserId(user.getId()); member.setProjectId(project.getId()); member.setUserLevel(defaultUserLevel); member.setStatus(TeamMember.STATUS_ADDED); member.setNotification(true); member.setEnteredBy(user.getId()); member.setModifiedBy(user.getId()); member.insert(db); if (autoCommit) { db.commit(); } // Success, now that the database is committed, invalidate the cache CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, user.getId()); CacheUtils.invalidateValue(Constants.SYSTEM_PROJECT_CACHE, project.getId()); } catch (Exception e) { LOG.error("addUserProfile", e); if (autoCommit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (autoCommit) { db.setAutoCommit(true); } } }
From source file:com.ibm.research.rdf.store.runtime.service.sql.StoreHelper.java
public static boolean setupAutoCommit(Connection conn) { try {/*from w ww . ja v a 2 s . co m*/ if (conn.getAutoCommit()) { conn.setAutoCommit(false); return true; } } catch (SQLException e) { } return false; }