List of usage examples for java.sql Statement getResultSet
ResultSet getResultSet() throws SQLException;
ResultSet
object. From source file:org.apache.stratos.status.monitor.core.jdbc.MySQLConnectionInitializer.java
/** * Gets the ServiceID, for the given product. * * @param product, name of the service/product * @return serviceID: int/*from w ww. java 2s . c o m*/ * @throws SQLException, if retrieving the service id failed. */ public static int getServiceID(String product) throws SQLException { Statement stmtCon = conn.createStatement(); String sql = StatusMonitorConstants.GET_SERVICE_ID_SQL_WSL_NAME_LIKE_SQL + "\"" + product + "\""; int serviceId = 0; ResultSet rs = stmtCon.getResultSet(); try { stmtCon.executeQuery(sql); while (rs.next()) { serviceId = rs.getInt(StatusMonitorConstants.ID); } } catch (SQLException e) { String msg = "Getting the serviceID failed"; log.error(msg, e); throw new SQLException(msg, e); } finally { rs.close(); stmtCon.close(); } return serviceId; }
From source file:org.apache.stratos.status.monitor.core.jdbc.MySQLConnectionInitializer.java
/** * Gets the ServiceStateID, for the given product/service. * * @param serviceID: int; ID of the service/product * @return serviceStateID: int//from ww w. ja v a 2s . c o m * @throws SQLException, if retrieving the service id failed. */ public static int getServiceStateID(int serviceID) throws SQLException { ResultSet rs; Statement stmtCon = conn.createStatement(); String sql = StatusMonitorConstants.GET_SERVICE_STATE_ID_SQL + serviceID + StatusMonitorConstants.ORDER_BY_TIMESTAMP_SQL; stmtCon.executeQuery(sql); rs = stmtCon.getResultSet(); int stateID = 0; try { while (rs.next()) { stateID = rs.getInt(StatusMonitorConstants.ID); } } catch (SQLException e) { String msg = "Getting the service state ID failed"; log.error(msg, e); throw new SQLException(msg, e); } finally { rs.close(); stmtCon.close(); } return stateID; }
From source file:net.xy.jcms.controller.configurations.parser.UsecaseDBConnector.java
/** * loads the usecases from the specified connection * //from w w w .j a v a 2 s . c o m * @param dac * @param connection * @return * @throws SQLException * @throws ClassNotFoundException */ private static Usecase[] loadUCs(final IDataAccessContext dac, final Connection connection, final ClassLoader parentLoader) throws SQLException, ClassNotFoundException { final Statement query = connection.createStatement(); if (!query.execute("SELECT * FROM Usecases WHERE Enabled = true;")) { throw new IllegalArgumentException("Retrieving usecases from DB returned no results."); } final ResultSet result = query.getResultSet(); final List<Usecase> cases = new LinkedList<Usecase>(); while (result.next()) { cases.add(loadUC(dac, result, connection, parentLoader)); } return cases.toArray(new Usecase[cases.size()]); }
From source file:ExecSQL.java
/** * Prints a result set./*from w ww .j a v a 2 s . com*/ * @param stat the statement whose result set should be printed */ public static void showResultSet(Statement stat) throws SQLException { ResultSet result = stat.getResultSet(); ResultSetMetaData metaData = result.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { if (i > 1) System.out.print(", "); System.out.print(metaData.getColumnLabel(i)); } System.out.println(); while (result.next()) { for (int i = 1; i <= columnCount; i++) { if (i > 1) System.out.print(", "); System.out.print(result.getString(i)); } System.out.println(); } result.close(); }
From source file:TerminalMonitor.java
static public void executeStatement(StringBuffer buff) throws SQLException { String sql = buff.toString(); Statement statement = null; try {//from ww w. j a va 2 s . co m statement = connection.createStatement(); if (statement.execute(sql)) { // true means the SQL was a SELECT processResults(statement.getResultSet()); } else { // no result sets, see how many rows were affected int num; switch (num = statement.getUpdateCount()) { case 0: System.out.println("No rows affected."); break; case 1: System.out.println(num + " row affected."); break; default: System.out.println(num + " rows affected."); } } } catch (SQLException e) { throw e; } finally { // close out the statement if (statement != null) { try { statement.close(); } catch (SQLException e) { } } } }
From source file:net.xy.jcms.controller.configurations.parser.UsecaseDBConnector.java
/** * loads the configurations from an extra table and uses the obmitted loader * to load dependencies./* ww w . j ava 2 s . c o m*/ * * @param uniqueId * to lookup the configs * @param connection * @param loader * @return * @throws SQLException */ private static Configuration<?>[] parseConfigurations(final String uniqueId, final Connection connection, final ClassLoader loader) throws SQLException { final Statement query = connection.createStatement(); if (!query.execute("SELECT * FROM Configurations WHERE usecaseUniqueId = " + uniqueId + ";")) { // no configurations defined LOG.warn("There are no configurations defined for usecase unique id: " + uniqueId); return new Configuration[] {}; } final ResultSet result = query.getResultSet(); final List<Configuration<?>> cases = new LinkedList<Configuration<?>>(); while (result.next()) { final String include = result.getString("include"); final ConfigurationType type = ConfigurationType.valueOf(result.getString("type")); if (StringUtils.isNotBlank(include)) { cases.add(Configuration.initConfigurationByInclude(type, include, loader)); } else { cases.add(Configuration.initByString(type, result.getString("value"), loader)); } } return cases.toArray(new Configuration[cases.size()]); }
From source file:org.andromda.dbtest.H2.java
/** * @param url//from w w w . j a v a 2 s. com * @param sqlFile */ public static void initDb(String url, String sqlFile) //throws SQLException, ClassNotFoundException { long now = System.currentTimeMillis(); try { Class.forName("org.h2.Driver"); // IF there are any errors in SQL Files, the connection throws an Exception List<String> sqls = new ArrayList<String>(); if (StringUtils.isNotBlank(sqlFile)) { // List of files separated by ; will be appended to URL and executed String[] files = StringUtils.split(sqlFile, ';'); // Files contain SQL statements separated by ; if (files.length > 0) { for (int i = 0; i < files.length; i++) { LOGGER.info("Parsing SQL file " + files[i]); sqls.addAll(fileToStrings(files[i], ';')); /*if (i==0) { url += ";INIT="; } else { // Separator for multiple files in the same init command url += "\\;"; } url += "RUNSCRIPT FROM '" + files[i] + "'";*/ } } } // Starts H2, allowing TCP connections also, to jdbc:h2:tcp://localhost/${sql.database} // Must use id/password with embedded persisted mode Connection conn = DriverManager.getConnection(url, "sa", "sa"); LOGGER.info("Connected to DB " + url + "\r in " + (System.currentTimeMillis() - now) + " ms"); long now1 = System.currentTimeMillis(); Statement stat = conn.createStatement(); int stmtCount = 0; int successfulCount = 0; for (String sql : sqls) { if (StringUtils.isNotBlank(sql)) { stmtCount++; boolean resultSet = false; try { resultSet = stat.execute(sql); if (resultSet) { ResultSet rset = stat.getResultSet(); LOGGER.info(sql + ";\r" + "ResultSet: " + rset + "\r"); try { rset.close(); } catch (Exception e) { LOGGER.error(e); } } else if (stat.getUpdateCount() > 0) { LOGGER.info(sql + ";\r" + "Updated rows: " + stat.getUpdateCount() + "\r"); } else if (StringUtils.containsIgnoreCase(sql, "INSERT INTO ") || StringUtils.containsIgnoreCase(sql, "UPDATE ") || StringUtils.containsIgnoreCase(sql, "DELETE ")) { LOGGER.info(sql + ";\rExecuted Successfully, no update or result\r"); } else { LOGGER.info(sql + ";\rExecuted Successfully\r"); } successfulCount++; } catch (SQLException e) { LOGGER.error(e); } } } LOGGER.info("Executed " + successfulCount + " out of " + stmtCount + " sql statements in " + (System.currentTimeMillis() - now1) + " ms, total time = " + (System.currentTimeMillis() - now) + " ms"); // Keep in-memory DB connection open after executing SQL statements int i = 1; while (i > 0) { // There is no Daemon option when starting DB through connection, just have to go into an infinite loop } } catch (IOException e) { LOGGER.error(e); } catch (ClassNotFoundException e) { LOGGER.error(e); } catch (SQLException e) { LOGGER.error(e); } }
From source file:com.wavemaker.runtime.data.util.JDBCUtils.java
public static Object runSql(String sql[], String url, String username, String password, String driverClassName, Log logger, boolean isDDL) { Connection con = getConnection(url, username, password, driverClassName); try {/*from w w w .j ava 2 s . c o m*/ try { con.setAutoCommit(true); } catch (SQLException ex) { throw new DataServiceRuntimeException(ex); } Statement s = con.createStatement(); try { try { for (String stmt : sql) { if (logger != null && logger.isInfoEnabled()) { logger.info("Running " + stmt); } s.execute(stmt); } if (!isDDL) { ResultSet r = s.getResultSet(); List<Object> rtn = new ArrayList<Object>(); while (r.next()) { // getting only the first col is pretty unuseful rtn.add(r.getObject(1)); } return rtn.toArray(new Object[rtn.size()]); } } catch (Exception ex) { if (logger != null && logger.isErrorEnabled()) { logger.error(ex.getMessage()); } throw ex; } } finally { try { s.close(); } catch (Exception ignore) { } } } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new DataServiceRuntimeException(ex); } } finally { try { con.close(); } catch (Exception ignore) { } } return null; }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * execute query/*from ww w.j a va 2 s .co m*/ * * @param userDB * @param strQuery * @param intStartCnt * @param intSelectLimitCnt * @return * @throws Exception */ public static QueryExecuteResultDTO executeQuery(final UserDBDAO userDB, String strSQL, final int intStartCnt, final int intSelectLimitCnt) throws Exception { ResultSet resultSet = null; java.sql.Connection javaConn = null; Statement statement = null; strSQL = SQLUtil.makeExecutableSQL(userDB, strSQL); try { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); javaConn = client.getDataSource().getConnection(); statement = javaConn.createStatement(); if (intStartCnt == 0) { statement.execute(strSQL); resultSet = statement.getResultSet(); } else { strSQL = PartQueryUtil.makeSelect(userDB, strSQL, intStartCnt, intSelectLimitCnt); if (logger.isDebugEnabled()) logger.debug("part sql called : " + strSQL); statement.execute(strSQL); resultSet = statement.getResultSet(); } return new QueryExecuteResultDTO(userDB, false, resultSet, intSelectLimitCnt, intStartCnt); } catch (Exception e) { logger.error("execute query", e); throw e; } finally { if (statement != null) statement.close(); if (resultSet != null) resultSet.close(); if (javaConn != null) javaConn.close(); } }
From source file:org.apache.stratos.status.monitor.agent.internal.core.MySQLConnector.java
/** * Gets the insert status//from w w w. j av a2 s . c o m * * @param ServiceID, id of the service * @return true, if insert status was successful * @throws SQLException, if writing to the database failed. */ public static boolean getInsertStatus(int ServiceID) throws SQLException { ResultSet rs = null; Statement stmtCon = null; boolean currentStatus = false; String sqlGetStateID = StatusMonitorConstants.SELECT_ALL_FROM_WSL_SERVICE_STATE_SQL + ServiceID + StatusMonitorConstants.ORDER_BY_TIMESTAMP_SQL_DESC_LIMIT_01_SQL; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date SystemDate = new Date(); dateFormat.format(SystemDate); int state_id; Date date; try { stmtCon = conn.createStatement(); stmtCon.executeQuery(sqlGetStateID); rs = stmtCon.getResultSet(); if (rs != null) { while (rs.next()) { state_id = rs.getInt(StatusMonitorConstants.STATE_ID); if (state_id == 1) { if (log.isDebugEnabled()) { log.debug("Up and Running :" + state_id); } currentStatus = true; } if (state_id == 2) { if (log.isDebugEnabled()) { log.debug("Broken :" + state_id); } currentStatus = true; } if (state_id == 4) { currentStatus = true; date = rs.getTimestamp(StatusMonitorConstants.TIMESTAMP); resolvedWSLID = rs.getInt(StatusMonitorConstants.ID); long currentTimeMs = SystemDate.getTime(); long resolvedTimeMs = date.getTime(); double time_diff = ((currentTimeMs - resolvedTimeMs) / (double) StatusMonitorConstants.HOUR_IN_MILLIS); if (log.isDebugEnabled()) { log.debug("State ID: " + state_id); } if (time_diff >= 1.0) { resolvedNotFixed = 1; } else { resolvedNotFixed = 2; } } } } else { currentStatus = true; } } catch (SQLException e) { String msg = "Getting Insert state failed"; log.error(msg, e); throw new SQLException(msg, e); } finally { if (rs != null) { rs.close(); } if (stmtCon != null) { stmtCon.close(); } } return currentStatus; }