List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.sludev.mssqlapplylog.MSSQLHelper.java
/** * Get a Connection for use with the current SQL Server Host. * @param sqlURL A SQL Server connection string * @param props Properties that should include the SQL Server username and password * @return A valid connection object or null on failure *///from www . jav a 2s .co m public static Connection getConn(String sqlURL, Properties props) { Connection conn = null; try { conn = DriverManager.getConnection(sqlURL, props); } catch (SQLException ex) { LOGGER.debug(String.format("Error getting connection. '%s'", sqlURL), ex); return null; } try { conn.setAutoCommit(true); } catch (SQLException ex) { LOGGER.error("Error setting autocommit() on connection.", ex); return null; } return conn; }
From source file:Main.java
private static void saveAll(Connection conn, List<Person> people) throws SQLException { PreparedStatement prep = conn.prepareStatement("insert into people values (?, ?);"); for (Person person : people) { prep.setString(1, person.getName()); prep.setString(2, person.getOccupation()); prep.addBatch();//from www. ja v a 2s.c o m } conn.setAutoCommit(false); prep.executeBatch(); conn.setAutoCommit(true); close(prep); }
From source file:net.codjo.dataprocess.server.treatmenthelper.TreatmentHelper.java
public static void initRepository(Connection con, List<RepositoryDescriptor> repositoryDescList) throws Exception { try {//from w w w . ja v a 2 s . co m con.setAutoCommit(false); LOG.info("Ajout des rfrentiels de traitement suivants :"); for (RepositoryDescriptor repositoryDesc : repositoryDescList) { deleteRepository(con, repositoryDesc.getRepositoryId()); insertAllRepositoryContent(con, repositoryDesc.getRepositoryId(), repositoryDesc.getRepositoryName(), repositoryDesc.getRepositoryPath()); insertRepository(con, repositoryDesc.getRepositoryId(), repositoryDesc.getRepositoryName()); } List<TreatmentFragment> treatmentFragmentList = checkIntegrityRepositoryContent(con); if (!treatmentFragmentList.isEmpty()) { String message = " est trop long ! : "; int maxLength = maxLengthTreatmentId(treatmentFragmentList) + message.length() + LENGTH; StringBuilder errorMessage = new StringBuilder(); errorMessage.append("\n").append(StringUtils.repeat("#", maxLength)); errorMessage.append("\n").append(StringUtils.repeat("+", maxLength)); for (TreatmentFragment treatmentFragment : treatmentFragmentList) { errorMessage.append("\n").append(treatmentFragment.getTreatmentId()).append(message) .append(treatmentFragment.getContentFragment()); } errorMessage.append("\n").append(StringUtils.repeat("+", maxLength)); errorMessage.append("\n").append(StringUtils.repeat("#", maxLength)); throw new TreatmentException(errorMessage.toString()); } else { con.commit(); LOG.info("Ajout termin avec succs !"); } } catch (Exception ex) { con.rollback(); LOG.error("\nErreur durant l'ajout des rfrentiels de traitement.\n!!! Rollback effectu !!!\n", ex); throw ex; } finally { con.setAutoCommit(true); } }
From source file:com.hangum.tadpole.rdb.core.util.bander.cubrid.CubridExecutePlanUtils.java
/** * cubrid execute plan/*w ww.j a v a 2s. c om*/ * * @param userDB * @param sql * @return * @throws Exception */ public static String plan(UserDBDAO userDB, String sql) throws Exception { if (!sql.toLowerCase().startsWith("select")) { logger.error("[cubrid execute plan ]" + sql); throw new Exception("This statment not select. please check."); } Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; try { Class.forName("cubrid.jdbc.driver.CUBRIDDriver"); conn = DriverManager.getConnection(userDB.getUrl(), userDB.getUsers(), userDB.getPasswd()); conn.setAutoCommit(false); // auto commit? false . sql = StringUtils.trim(sql).substring(6); if (logger.isDebugEnabled()) logger.debug("[qubrid modifying query]" + sql); sql = "select " + RECOMPILE + sql; pstmt = conn.prepareStatement(sql); ((CUBRIDStatement) pstmt).setQueryInfo(true); rs = pstmt.executeQuery(); String plan = ((CUBRIDStatement) pstmt).getQueryplan(); // ? . conn.commit(); if (logger.isDebugEnabled()) logger.debug("cubrid plan text : " + plan); return plan; } finally { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } }
From source file:com.example.querybuilder.server.Jdbc.java
public static <V> V executeTransaction(Connection connection, Callable<V> callable) { try {// w w w .j a v a 2s . c o m try { connection.setAutoCommit(false); V value = callable.call(); return value; } finally { connection.setAutoCommit(true); } } catch (SQLException e) { throw new SqlRuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java
private static void close(Connection connection, boolean restoreAutoCommit) { if (connection != null) { try {//from w ww. j av a 2s . c o m if (restoreAutoCommit) { connection.setAutoCommit(true); } connection.close(); } catch (SQLException e) { // Do nothing } } }
From source file:com.krawler.database.DbPool.java
/** * Returns a new database connection for maintenance operations, such as * restore. Does not specify the name of the default database. This * connection is created outside the context of the database connection * pool./*from www .j a v a 2 s .c o m*/ */ public static Connection getMaintenanceConnection() throws ServiceException { try { String user = ConfigReader.getinstance().get("mysql_user", "root"); String pwd = ConfigReader.getinstance().get("mysql_passwd", "root"); java.sql.Connection conn = DriverManager.getConnection(sRootUrl + "?user=" + user + "&password=" + pwd); conn.setAutoCommit(false); return new Connection(conn); } catch (SQLException e) { throw ServiceException.FAILURE("getting database maintenance connection", e); } }
From source file:com.laudandjolynn.mytv.Main.java
/** * ??/* ww w . ja v a2 s .c om*/ */ private static void initDb(MyTvData data) { if (data.isDbInited()) { logger.debug("db have already init."); return; } File myTvDataFilePath = new File(Constant.MY_TV_DATA_FILE_PATH); Connection conn = null; Statement stmt = null; try { conn = DataSourceManager.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); List<String> sqlList = loadSql(); for (String sql : sqlList) { stmt.addBatch(sql); logger.info("execute sql: " + sql); } stmt.executeBatch(); conn.commit(); DataSourceManager.DATA_SOURCE_PROP.remove(DataSourceManager.RES_KEY_DB_SQL_LIST); data.writeData(null, Constant.XML_TAG_DB, "true"); } catch (SQLException e) { if (conn != null) { try { conn.rollback(); } catch (SQLException e1) { throw new MyTvException("error occur while rollback transaction.", e); } } myTvDataFilePath.deleteOnExit(); throw new MyTvException("error occur while execute sql on db.", e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { throw new MyTvException("error occur while close statement.", e); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { throw new MyTvException("error occur while close sqlite connection.", e); } } } }
From source file:com.laudandjolynn.mytv.Main.java
/** * ???/*from ww w. j a v a 2 s . c om*/ */ private static void initDbData0(MyTvData data) { if (data.isDataInited()) { logger.info("init data had insert into db."); return; } Properties tvStationProp = new Properties(); try { tvStationProp.load(Main.class.getResourceAsStream("/" + Constant.TV_STATION_INIT_DATA_FILE_NAME)); } catch (IOException e) { throw new MyTvException( "error occur while load property file: " + Constant.TV_STATION_INIT_DATA_FILE_NAME, e); } Collection<Object> values = tvStationProp.values(); List<String> insertSqlList = new ArrayList<String>(values.size()); String insertSql = "insert into my_tv (stationName,displayName,classify,channel,sequence)"; for (Object value : values) { insertSqlList.add(insertSql + " values (" + value.toString() + ")"); } Connection conn = null; Statement stmt = null; try { conn = DataSourceManager.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); for (String sql : insertSqlList) { stmt.addBatch(sql); logger.info("execute sql: " + sql); } stmt.executeBatch(); conn.commit(); data.writeData(null, Constant.XML_TAG_DATA, "true"); } catch (SQLException e) { if (conn != null) { try { conn.rollback(); } catch (SQLException e1) { throw new MyTvException("error occur while rollback transaction.", e1); } } throw new MyTvException("error occur while execute sql on db.", e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { throw new MyTvException("error occur while close statement.", e); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { throw new MyTvException("error occur while close sqlite connection.", e); } } } }
From source file:com.medlog.webservice.services.tone.ToneProcessorFactory.java
private static ArrayList<Integer> processTone(DbConnection dbc, ToneAnalysis tone, int diaryID) { CallableStatement cs = null;/* ww w. ja v a 2 s. c om*/ String cat_id = ""; ArrayList<Integer> results = new ArrayList<Integer>(); try { //category , tone , sentance,score,text List<com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory> to = tone.getDocumentTone() .getTones(); Connection conn = dbc.getConnnection(); cs = conn.prepareCall(new StringBuilder().append("{call spDiaryTextScoreInsert(").append(diaryID) .append(",?,?,?,?,?)}").toString()); conn.setAutoCommit(false); cs.setInt(3, 0); cs.setNull(5, java.sql.Types.NVARCHAR);// cat_id); for (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory docTC : to) { cat_id = docTC.getId(); cs.setString(1, cat_id); for (ToneScore s : docTC.getTones()) { cs.setString(2, s.getId()); cs.setDouble(4, s.getScore()); cs.addBatch(); } } System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() Process " + tone.getSentencesTone().size() + " sentances."); int[] docRes = cs.executeBatch(); List l = Arrays.asList(docRes); results.addAll(l); cs.clearBatch(); System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result --- " + ArrayUtils.toString(docRes)); int[] sentRes = null; for (SentenceTone sentT : tone.getSentencesTone()) { to = sentT.getTones(); cs.setInt(3, sentT.getId()); cs.setString(5, toS(sentT.getText()).trim()); for (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory docTC : to) { cat_id = docTC.getId(); cs.setString(1, cat_id); try { for (ToneScore s : docTC.getTones()) { cs.setString(2, s.getId()); cs.setDouble(4, s.getScore()); cs.addBatch(); } if (DEBUG) { DbUtl.getWarningsFromStatement(cs); } // sentRes = cs.executeBatch(); // List l = Arrays.asList(sentRes); // results.addAll(l); } catch (SQLException s) { System.err.println( "com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(loop)" + DbUtl.printJDBCExceptionMsg(s)); s.printStackTrace(); } catch (Exception s) { } System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result[" + sentT.getId() + "] " + ArrayUtils.toString(sentRes)); } } sentRes = cs.executeBatch(); try { l = Arrays.asList(sentRes); results.addAll(l); conn.setAutoCommit(true); cs.clearBatch(); } catch (Exception e) { e.printStackTrace(); try { conn.setAutoCommit(true); } catch (Exception eeee) { eeee.printStackTrace(); } } } catch (BatchUpdateException ex) { Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex); System.err.println("com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(batch)" + DbUtl.printBatchUpdateException(ex)); } catch (SQLTimeoutException ex) { Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (SQLException ex) { Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex); System.err.println("com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(meth)" + DbUtl.printJDBCExceptionMsg(ex)); } finally { DbUtl.close(cs); } return results; }