List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:org.kawanfw.sql.servlet.executor.ServerSqlExecutorNew.java
/** * Execute the Sql Action/*from w ww . ja v a2 s . c o m*/ */ private void execute() throws IOException, SQLException, IllegalArgumentException { String username = request.getParameter(Parameter.USERNAME); String connectionId = request.getParameter(ConnectionParms.CONNECTION_ID); String conHolderParam = request.getParameter(SqlAction.CONNECTION_HOLDER); String statementHolderParam = request.getParameter(SqlAction.STATEMENT_HOLDER); debug("SqlAction.CONNECTION_HOLDER: " + conHolderParam); debug("SqlAction.STATEMENT_HOLDER : " + statementHolderParam); Connection connection = null; List<File> tempFilesForResultSet = new Vector<File>(); if (connectionId.equals("0")) { try { connection = commonsConfigurator.getConnection(); ServerSqlUtil.setConnectionProperties(conHolderParam, connection); if (statementHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) { String fileName = StringUtils.substringAfter(statementHolderParam, TransportConverter.KAWANFW_BYTES_STREAM_FILE); // Param contains only the file to read from the statements executeStatementsFromFile(username, fileName, connection, tempFilesForResultSet); } else { // All statements are in single param executeStatementsFromList(username, statementHolderParam, connection, tempFilesForResultSet); } if (!connection.getAutoCommit()) { connection.commit(); } } catch (IOException e) { if (!connection.getAutoCommit()) { connection.rollback(); } throw e; } catch (SQLException e) { if (!connection.getAutoCommit()) { connection.rollback(); } throw e; } finally { // Release the connection ConnectionCloser.freeConnection(connection, sqlConfigurator); } } else { ConnectionStore connectionStore = new ConnectionStore(username, connectionId); connection = connectionStore.get(); if (connection == null) { //out.println(TransferStatus.SEND_OK); //out.println(SqlReturnCode.SESSION_INVALIDATED); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, SqlReturnCode.SESSION_INVALIDATED); return; } if (statementHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) { String fileName = StringUtils.substringAfter(statementHolderParam, TransportConverter.KAWANFW_BYTES_STREAM_FILE); // Param contains only the file to read from the statements executeStatementsFromFile(username, fileName, connection, tempFilesForResultSet); } else { // All statements are in single param executeStatementsFromList(username, statementHolderParam, connection, tempFilesForResultSet); } } // Of, if the list is not empty, dump it to out on servlet out stream FileDumper.dumpFile(tempFilesForResultSet, out); }
From source file:org.kawanfw.sql.servlet.executor.ServerSqlExecutorCallable.java
/** * Execute the Callable Statement// w w w.j a v a 2 s . c o m * * @throws IOException * @throws SQLException * @throws IllegalArgumentException */ public void callStatement() throws IOException, SQLException, IllegalArgumentException { String username = request.getParameter(Parameter.USERNAME); String connectionId = request.getParameter(ConnectionParms.CONNECTION_ID); String conHolderParam = request.getParameter(SqlAction.CONNECTION_HOLDER); String statementHolderParam = request.getParameter(SqlAction.STATEMENT_HOLDER); debug("SqlAction.CONNECTION_HOLDER: " + conHolderParam); debug("SqlAction.STATEMENT_HOLDER : " + statementHolderParam); Connection connection = null; List<File> tempFilesForResultSet = new Vector<File>(); if (connectionId.equals("0")) { // stateless mode was set on PC try { connection = commonsConfigurator.getConnection(); ServerSqlUtil.setConnectionProperties(conHolderParam, connection); if (statementHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) { String fileName = StringUtils.substringAfter(statementHolderParam, TransportConverter.KAWANFW_BYTES_STREAM_FILE); // Param contains only the file to read from the statements callStatementsFromFile(username, fileName, connection, tempFilesForResultSet); } else { // All statements are in single param callStatementsFromList(username, statementHolderParam, connection, tempFilesForResultSet); } if (!connection.getAutoCommit()) { connection.commit(); } } catch (IOException e) { if (!connection.getAutoCommit()) { connection.rollback(); } throw e; } catch (SQLException e) { if (!connection.getAutoCommit()) { connection.rollback(); } throw e; } finally { // Release the connection ConnectionCloser.freeConnection(connection, sqlConfigurator); } } else { ConnectionStore connectionStore = new ConnectionStore(username, connectionId); connection = connectionStore.get(); if (connection == null) { //out.println(TransferStatus.SEND_OK); //out.println(SqlReturnCode.SESSION_INVALIDATED); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, SqlReturnCode.SESSION_INVALIDATED); return; } if (statementHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) { String fileName = StringUtils.substringAfter(statementHolderParam, TransportConverter.KAWANFW_BYTES_STREAM_FILE); // Param contains only the file to read from the statements callStatementsFromFile(username, fileName, connection, tempFilesForResultSet); } else { // All statements are in single param callStatementsFromList(username, statementHolderParam, connection, tempFilesForResultSet); } } // Of, if the list is not empty, dump it to out on servlet out stream FileDumper.dumpFile(tempFilesForResultSet, out); }
From source file:org.sakaiproject.nakamura.lite.storage.jdbc.JDBCStorageClient.java
private boolean startBlock() throws SQLException { Connection connection = jcbcStorageClientConnection.getConnection(); boolean autoCommit = connection.getAutoCommit(); connection.setAutoCommit(false);/*www . java 2 s .c o m*/ return autoCommit; }
From source file:weave.utils.SQLUtils.java
public static void copyCsvToDatabase(Connection conn, String formatted_CSV_path, String sqlSchema, String sqlTable) throws SQLException, IOException { String dbms = conn.getMetaData().getDatabaseProductName(); Statement stmt = null;//from w w w . j a va 2s .com String quotedTable = quoteSchemaTable(conn, sqlSchema, sqlTable); try { if (dbms.equalsIgnoreCase(SQLUtils.MYSQL)) { stmt = conn.createStatement(); //ignoring 1st line so that we don't put the column headers as the first row of data stmt.executeUpdate(String.format( "load data local infile '%s' into table %s fields terminated by ',' enclosed by '\"' lines terminated by '\\n' ignore 1 lines", formatted_CSV_path, quotedTable)); stmt.close(); } else if (dbms.equalsIgnoreCase(SQLUtils.ORACLE)) { // Insert each row repeatedly boolean prevAutoCommit = conn.getAutoCommit(); if (prevAutoCommit) conn.setAutoCommit(false); String csvData = org.apache.commons.io.FileUtils.readFileToString(new File(formatted_CSV_path)); String[][] rows = CSVParser.defaultParser.parseCSV(csvData); String query = "", tempQuery = "INSERT INTO %s values ("; for (int column = 0; column < rows[0].length; column++) // Use header row to determine the number of columns { if (column == rows[0].length - 1) tempQuery = tempQuery + "?)"; else tempQuery = tempQuery + "?,"; } query = String.format(tempQuery, quotedTable); CallableStatement cstmt = null; try { cstmt = conn.prepareCall(query); ; for (int row = 1; row < rows.length; row++) //Skip header line { for (int column = 0; column < rows[row].length; column++) { cstmt.setString(column + 1, rows[row][column]); } cstmt.execute(); } } catch (SQLException e) { throw new RemoteException(e.getMessage(), e); } finally { SQLUtils.cleanup(cstmt); } } else if (dbms.equalsIgnoreCase(SQLUtils.POSTGRESQL)) { ((PGConnection) conn).getCopyAPI().copyIn( String.format("COPY %s FROM STDIN WITH CSV HEADER", quotedTable), new FileInputStream(formatted_CSV_path)); } else if (dbms.equalsIgnoreCase(SQLUtils.SQLSERVER)) { stmt = conn.createStatement(); // sql server expects the actual EOL character '\n', and not the textual representation '\\n' stmt.executeUpdate(String.format( "BULK INSERT %s FROM '%s' WITH ( FIRSTROW = 2, FIELDTERMINATOR = '%s', ROWTERMINATOR = '\n', KEEPNULLS )", quotedTable, formatted_CSV_path, SQL_SERVER_DELIMETER)); } } finally { SQLUtils.cleanup(stmt); } }
From source file:org.alinous.plugin.derby.DerbyDataSource.java
public void readLargeObject(Object connectionHandle, String fileName, String table, String blobColumn, WhereClause where, PostContext context, VariableRepository provider) throws ExecutionException { // SELECT blobColumn FROM table WHERE ... SelectSentence sentence = new SelectSentence(); FromClause from = new FromClause(); TablesList tableList = new TablesList(); tableList.addTable(new TableIdentifier(table)); from.setTableList(tableList);/*ww w . j a v a2s.com*/ sentence.setFrom(from); TypeHelper helper = this.typeHelper.newHelper(false, sentence); StringBuffer buff = new StringBuffer(); buff.append("SELECT "); buff.append(blobColumn); buff.append(" FROM "); buff.append(table); if (where != null && where.isReady(context, provider, null)) { buff.append(" "); buff.append(where.extract(context, provider, null, null, helper)); } OutputStream output = null; InputStream input = null; Connection con = (Connection) connectionHandle; boolean lastAutoCommit = false; try { lastAutoCommit = con.getAutoCommit(); if (lastAutoCommit == true) { con.setAutoCommit(false); } Statement statement = con.createStatement(); ResultSet result = statement.executeQuery(buff.toString()); result.next(); output = new AlinousFileOutputStream(new AlinousFile(fileName)); input = result.getBinaryStream(1); byte[] byteBuff = new byte[256]; int n = 1; while (n > 0) { n = input.read(byteBuff); if (n <= 0) { break; } output.write(byteBuff, 0, n); } statement.close(); } catch (SQLException e) { throw new ExecutionException(e, "Failed in reading blob"); // i18n } catch (IOException e) { throw new ExecutionException(e, "Failed in reading blob"); // i18n } finally { try { if (input != null) { input.close(); } } catch (IOException e) { } if (output != null) { try { output.close(); } catch (IOException e) { } } try { if (lastAutoCommit == true) { con.setAutoCommit(lastAutoCommit); } } catch (SQLException e) { } } }
From source file:org.apache.slide.store.impl.rdbms.JDBCStore.java
protected Connection getNewConnection() throws SQLException { Connection connection; if (useDbcpPooling) { try {//ww w .j av a 2 s . c o m connection = DriverManager.getConnection(DBCP_URL + ":" + dbcpPoolName); } catch (SQLException e) { getLogger().log("Could not create connection. Reason: " + e, LOG_CHANNEL, Logger.EMERGENCY); throw e; } } else { try { connection = DriverManager.getConnection(url, user, password); } catch (SQLException e) { getLogger().log("Could not create connection. Reason: " + e, LOG_CHANNEL, Logger.EMERGENCY); throw e; } try { if (connection.getTransactionIsolation() != isolationLevel) { connection.setTransactionIsolation(isolationLevel); } } catch (SQLException e) { getLogger().log("Could not set isolation level '" + isolationLevelToString(isolationLevel) + "'. Reason: " + e, LOG_CHANNEL, Logger.WARNING); } if (connection.getAutoCommit()) { connection.setAutoCommit(false); } } return connection; }
From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
@Override public void openTransaction() throws ODataServiceFault { try {// ww w.ja v a 2 s. com if (getTransactionalConnection() == null) { Connection connection = this.dataSource.getConnection(); this.defaultAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); this.defaultTransactionalIsolation = connection.getTransactionIsolation(); connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); transactionalConnection.set(connection); } } catch (SQLException e) { throw new ODataServiceFault(e, "Connection Error occurred. :" + e.getMessage()); } }
From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
private void commitExecution(Connection connection) throws SQLException { if (getTransactionalConnection() == null) { if (!connection.getAutoCommit()) { connection.commit();//from w w w . jav a 2s .c om } } }
From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java
/** * Method to delete client certificate from the database. * * @param apiIdentifier : Identifier of the API. * @param alias : Alias for the certificate. * @param tenantId : The Id of the tenant who owns the certificate. * @return : true if certificate deletion is successful, false otherwise. *//* w w w . j a v a 2 s .co m*/ public boolean deleteClientCertificate(APIIdentifier apiIdentifier, String alias, int tenantId, Connection connection) throws CertificateManagementException { PreparedStatement preparedStatement = null; boolean result = false; boolean isConnectionNew = false; String deleteCertQuery = SQLConstants.ClientCertificateConstants.PRE_DELETE_CERTIFICATES; if (apiIdentifier == null) { deleteCertQuery = SQLConstants.ClientCertificateConstants.PRE_DELETE_CERTIFICATES_WITHOUT_APIID; } try { if (connection == null) { isConnectionNew = true; connection = APIMgtDBUtil.getConnection(); initialAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); } int apiId = 0; if (apiIdentifier != null) { apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, connection); } /* If an entry exists already with "Removed" true, remove that particular entry and update the current entry with removed true */ preparedStatement = connection.prepareStatement(deleteCertQuery); preparedStatement.setInt(1, tenantId); preparedStatement.setBoolean(2, true); preparedStatement.setString(3, alias); if (apiIdentifier != null) { preparedStatement.setInt(4, apiId); } preparedStatement.executeUpdate(); deleteCertQuery = SQLConstants.ClientCertificateConstants.DELETE_CERTIFICATES; if (apiIdentifier == null) { deleteCertQuery = SQLConstants.ClientCertificateConstants.DELETE_CERTIFICATES_WITHOUT_APIID; } preparedStatement = connection.prepareStatement(deleteCertQuery); preparedStatement.setBoolean(1, true); preparedStatement.setInt(2, tenantId); preparedStatement.setString(3, alias); if (apiIdentifier != null) { preparedStatement.setInt(4, apiId); } result = preparedStatement.executeUpdate() >= 1; if (isConnectionNew) { connection.commit(); } } catch (SQLException e) { handleConnectionRollBack(connection); handleException("Database exception while deleting client certificate metadata for the alias " + alias, e); } catch (APIManagementException e) { handleConnectionRollBack(connection); handleException( "API Management exception while trying deleting certificate metadata with the alias " + alias, e); } finally { if (isConnectionNew) { APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit); APIMgtDBUtil.closeAllConnections(preparedStatement, connection, null); } else { APIMgtDBUtil.closeAllConnections(preparedStatement, null, null); } } return result; }
From source file:com.draagon.meta.manager.db.ObjectManagerDB.java
/** * Checks to see if a transaction exists or not */// ww w . ja v a 2 s. co m protected void checkTransaction(Connection c, boolean throwEx) throws MetaException { try { if (enforceTransaction() && c.getAutoCommit()) { MetaException me = new MetaException( "The connection retrieved is not operating under a transaction and transactions are being enforced"); if (throwEx) { throw me; } else { log.warn(me.getMessage(), me); } } } catch (SQLException e) { throw new MetaException("Error checking connection for transaction enforcement: " + e.getMessage(), e); } }