List of usage examples for java.sql PreparedStatement close
void close() throws SQLException;
Statement
object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. From source file:com.concursive.connect.web.modules.activity.utils.ProjectHistoryUtils.java
public static int queryAdditionalCommentsCount(Connection db, ProjectHistory projectHistory) throws SQLException { int count = 0; int topId = projectHistory.getTopId(); if (topId == -1) { topId = projectHistory.getId();//from w w w. ja v a2 s. c o m } PreparedStatement pst = db.prepareStatement("SELECT count(*) AS comment_count " + "FROM project_history " + "WHERE top_id = ? AND position > ? "); pst.setInt(1, topId); pst.setInt(2, projectHistory.getPosition()); ResultSet rs = pst.executeQuery(); if (rs.next()) { count = rs.getInt("comment_count"); } rs.close(); pst.close(); return count; }
From source file:com.concursive.connect.web.modules.upgrade.utils.UpgradeUtils.java
/** * Queries the database to see if the script has already been executed * * @param db Description of the Parameter * @param version Description of the Parameter * @return The installed value//from ww w . j a v a2 s .c om * @throws java.sql.SQLException Description of the Exception */ public static boolean isInstalled(Connection db, String version) throws SQLException { boolean isInstalled = false; // Query the installed version PreparedStatement pst = db.prepareStatement( "SELECT script_version " + "FROM database_version " + "WHERE script_version = ? "); pst.setString(1, version); ResultSet rs = pst.executeQuery(); if (rs.next()) { isInstalled = true; } rs.close(); pst.close(); return isInstalled; }
From source file:com.splicemachine.tutorials.model.RULPredictiveModel.java
/** * Stored Procedure for Predictions// w w w .j a v a 2 s. com */ public static void predictRUL(String sensorTableName, String resultsTableName, String savedModelPath, int loopinterval) { try { //Initialize variables if (sensorTableName == null || sensorTableName.length() == 0) sensorTableName = "IOT.SENSOR_AGG_1_VIEW"; if (resultsTableName == null || resultsTableName.length() == 0) resultsTableName = "IOT.PREDICTION_EXT"; if (savedModelPath == null || savedModelPath.length() == 0) savedModelPath = "/tmp"; if (!savedModelPath.endsWith("/")) savedModelPath = savedModelPath + "/"; savedModelPath += "model/"; String jdbcUrl = "jdbc:splice://localhost:1527/splicedb;user=splice;password=admin;useSpark=true"; Connection conn = DriverManager.getConnection(jdbcUrl); SparkSession sparkSession = SpliceSpark.getSession(); //Specify the data for predictions Map<String, String> options = new HashMap<String, String>(); options.put("driver", "com.splicemachine.db.jdbc.ClientDriver"); options.put("url", jdbcUrl); options.put("dbtable", sensorTableName); //Load Model to use for predictins CrossValidatorModel cvModel = CrossValidatorModel.load(savedModelPath); //Keep checking for new data and make predictions while (loopinterval > 0) { //Sensor data requiring predictions Dataset<Row> sensords = sparkSession.read().format("jdbc").options(options).load(); //prepare data sensords = sensords.na().fill(0); //make predictions Dataset<Row> predictions = cvModel.transform(sensords) .select("ENGINE_TYPE", "UNIT", "TIME", "prediction") .withColumnRenamed("prediction", "PREDICTION"); //Save predictions String fileName = "temp_pred_" + RandomStringUtils.randomAlphabetic(6).toLowerCase(); predictions.write().mode(SaveMode.Append).csv("/tmp/data_pred/predictions"); //Mark records for which predictions are made PreparedStatement pStmtDel = conn.prepareStatement( "delete from IOT.TO_PROCESS_SENSOR s where exists (select 1 from IOT.PREDICTIONS_EXT p where p.engine_type = s.engine_type and p.unit= s.unit and p.time=s.time )"); pStmtDel.execute(); pStmtDel.close(); } } catch (SQLException sqle) { System.out.println("Error :::::" + sqle.toString()); LOG.error("Exception in getColumnStatistics", sqle); sqle.printStackTrace(); } }
From source file:com.wso2telco.core.dbutils.DbUtils.java
/** * Close statement.//from w w w . ja v a 2 s . c o m * * @param preparedStatement * the prepared statement */ private static void closeStatement(PreparedStatement preparedStatement) { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { log.warn("Database error. Could not close PreparedStatement. Continuing with" + " others. - " + e.getMessage(), e); } } }
From source file:com.l2jfree.gameserver.instancemanager.CursedWeaponsManager.java
public static void removeFromDb(int itemId) { Connection con = null;//from w w w . j av a 2s .c o m try { con = L2DatabaseFactory.getInstance().getConnection(con); // Delete datas PreparedStatement statement = con.prepareStatement("DELETE FROM cursed_weapons WHERE itemId = ?"); statement.setInt(1, itemId); statement.executeUpdate(); statement.close(); } catch (SQLException e) { _log.fatal("CursedWeaponsManager: Failed to remove data: ", e); } finally { L2DatabaseFactory.close(con); } }
From source file:net.codjo.dataprocess.server.treatmenthelper.TreatmentHelper.java
public static void insertRepository(Connection con, int repositoryId, String repositoryName) throws SQLException { PreparedStatement pStmt = con .prepareStatement("insert into PM_REPOSITORY (REPOSITORY_ID, REPOSITORY_NAME) values (?, ?)"); try {//from w ww .ja va 2s. com pStmt.setInt(1, repositoryId); pStmt.setString(2, repositoryName); pStmt.executeUpdate(); } finally { pStmt.close(); } }
From source file:io.cloudslang.content.database.services.SQLCommandService.java
public static String executeSqlCommand(final SQLInputs sqlInputs) throws Exception { final ConnectionService connectionService = new ConnectionService(); try (final Connection connection = connectionService.setUpConnection(sqlInputs)) { connection.setReadOnly(false);//w w w . java 2s .c o m final String dbType = sqlInputs.getDbType(); if (ORACLE_DB_TYPE.equalsIgnoreCase(dbType) && sqlInputs.getSqlCommand().toLowerCase().contains(DBMS_OUTPUT)) { final PreparedStatement preparedStatement = connection.prepareStatement(sqlInputs.getSqlCommand()); preparedStatement.setQueryTimeout(sqlInputs.getTimeout()); OracleDbmsOutput oracleDbmsOutput = new OracleDbmsOutput(connection); preparedStatement.executeQuery(); sqlInputs.setIUpdateCount(preparedStatement.getUpdateCount()); preparedStatement.close(); final String output = oracleDbmsOutput.getOutput(); oracleDbmsOutput.close(); return output; } else { final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency()); statement.setQueryTimeout(sqlInputs.getTimeout()); try { statement.execute(sqlInputs.getSqlCommand()); } catch (SQLException e) { if (SYBASE_DB_TYPE.equalsIgnoreCase(dbType)) { //during a dump sybase sends back status as exceptions. if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dump")) { return SQLUtils.processDumpException(e); } else if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("load")) { return SQLUtils.processLoadException(e); } } else { throw e; } } ResultSet rs = statement.getResultSet(); if (rs != null) { ResultSetMetaData rsMtd = rs.getMetaData(); if (rsMtd != null) { sqlInputs.getLRows().clear(); int colCount = rsMtd.getColumnCount(); if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) { while (rs.next()) { if (colCount >= 4) { sqlInputs.getLRows().add(rs.getString(4)); } } } else { String delimiter = (StringUtils.isNoneEmpty(sqlInputs.getStrDelim())) ? sqlInputs.getStrDelim() : ","; String strRowHolder; while (rs.next()) { strRowHolder = ""; for (int i = 1; i <= colCount; i++) { if (i > 1) { strRowHolder += delimiter; } strRowHolder += rs.getString(i); } sqlInputs.getLRows().add(strRowHolder); } } rs.close(); } } //For sybase, when dbcc command is executed, the result is shown in warning message else if (dbType.equalsIgnoreCase(SYBASE_DB_TYPE) && sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) { SQLWarning warning = statement.getWarnings(); while (warning != null) { sqlInputs.getLRows().add(warning.getMessage()); warning = warning.getNextWarning(); } } sqlInputs.setIUpdateCount(statement.getUpdateCount()); } } return "Command completed successfully"; }
From source file:com.nabla.dc.server.handler.fixed_asset.Asset.java
static private int getAssetDepreciationBeforeDisposal(final Connection conn, int assetId) throws SQLException { final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT SUM(amount) FROM fa_transaction WHERE fa_asset_id=? AND class='DEP';", assetId); try {//w w w. j a v a 2 s . com final ResultSet rs = stmt.executeQuery(); try { return rs.next() ? rs.getInt(1) : 0; } finally { rs.close(); } } finally { stmt.close(); } }
From source file:at.becast.youploader.database.SQLite.java
/** * A simple SQL query without any return. * //from w w w.j a v a2 s . com * @param sql The SQL query * @throws SQLException */ public static void query(String sql) throws SQLException { PreparedStatement prest = null; prest = c.prepareStatement(sql); prest.executeUpdate(); prest.close(); }
From source file:com.nabla.dc.server.handler.fixed_asset.Asset.java
static private int getAssetCostBeforeDisposal(final Connection conn, int assetId) throws SQLException { final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT SUM(amount) FROM fa_transaction WHERE fa_asset_id=? AND class='COST';", assetId); try {//from w w w . ja va2 s. c o m final ResultSet rs = stmt.executeQuery(); try { return rs.next() ? rs.getInt(1) : 0; } finally { rs.close(); } } finally { stmt.close(); } }