List of usage examples for java.sql ResultSet last
boolean last() throws SQLException;
ResultSet
object. From source file:com.snowy.data.java
public ArrayList<ArrayList<Integer>> getGameBoard(int id) { /*/*w w w.java 2 s . co m*/ 1 2 3 4 5 6 7 1 01|02|03|04|05|06|07 2 08|09|10|11|12|13|14 3 15|16|17|18|19|20|21 4 22|23|24|25|26|27|28 5 29|30|31|32|33|34|35 6 36|37|38|39|40|41|42 */ ArrayList<ArrayList<Integer>> returns = new ArrayList<>(); try { PreparedStatement ps = con.prepareStatement("Select LastKnownState from game where GameId=?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); rs.last(); String boardString = rs.getString("LastKnownState"); char[] boardCharArray = boardString.toCharArray(); for (int i = 0; i < boardCharArray.length; i += 7) { ArrayList<Integer> in = new ArrayList<>(); for (int x = 0; x < 7; x++) { in.add(Integer.parseInt(String.valueOf(boardCharArray[i + x]))); } returns.add(in); } //rs.close(); //ps.close(); } catch (SQLException ex) { Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex); } return returns; }
From source file:com.snowy.data.java
public String createUser(String username, String password, String email) { String responce = ""; try {/*from w ww. j a v a 2 s. co m*/ PreparedStatement ps = con.prepareStatement("select * from users where Username =?"); ps.setString(1, username); ResultSet rs = ps.executeQuery(); rs.last(); if (rs.getRow() == 0) { ps = con.prepareStatement("select * from users where Email=?"); ps.setString(1, email); rs = ps.executeQuery(); rs.last(); if (rs.getRow() == 0) { ps = con.prepareStatement( "insert into users (Username,Password,Email,timeoutTime) values (?,?,?,0)"); ps.setString(1, username); ps.setString(2, PasswordHash.createHash(password)); ps.setString(3, email); if (ps.executeUpdate() == 1) { return "Creation Sucess"; } else { return "Creation Failure"; } } else { responce = "Email Exists"; } } else { responce = "Username Exists"; } //ps.close(); //rs.close(); } catch (SQLException | PasswordHash.CannotPerformOperationException ex) { Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex); } return responce; }
From source file:ca.on.gov.jus.icon.common.iconcodetables.IconCodeTablesManager.java
private IconCodeTable getICONCodesTableList() { IconCodeTable iconCodesTableList = null; String selectSql = null;//from w w w. j av a2 s .c o m Connection oracleConnection = ReportsConnectionManager.getPooledOracleConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; if (null != oracleConnection) { selectSql = "" + "SELECT " + " ICONADMIN.ICON_TABLES_CODE.CODE, " + " ICONADMIN.ICON_TABLES_CODE.DESCRIPTION, " + " ICONADMIN.ICON_TABLES_CODE.TABLE_PASS " + "FROM " + " ICONADMIN.ICON_TABLES_CODE " + "ORDER BY " + " ICONADMIN.ICON_TABLES_CODE.DESCRIPTION ASC "; try { preparedStatement = oracleConnection.prepareStatement(selectSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); resultSet = preparedStatement.executeQuery(); resultSet.last(); int resultSetCount = resultSet.getRow(); //logger.info("resultSetCount: " + resultSetCount); resultSet.beforeFirst(); if (resultSetCount > 0) { iconCodesTableList = new IconCodeTable("ICON_CodeTablesList", "ICON Codes Table List"); } while (resultSet.next()) { IconCodeTable iconCodeTable = new IconCodeTable(resultSet.getString("CODE"), resultSet.getString("DESCRIPTION")); iconCodeTable.setCodeTablePass(resultSet.getString("TABLE_PASS")); //Null it so that it can not be used that way iconCodeTable.setCodeTableValues(null); iconCodesTableList.getCodeTableValues().put(resultSet.getString("CODE"), iconCodeTable); } } catch (SQLException e) { e.printStackTrace(); } finally { try { //clean up if (null != resultSet) { resultSet.close(); resultSet = null; } if (null != preparedStatement) { preparedStatement.close(); preparedStatement = null; } //Should never close the pooled connection // if(null != oracleConnection){ // oracleConnection.close(); // oracleConnection = null; // } } catch (SQLException e1) { } } } return iconCodesTableList; }
From source file:com.chiorichan.database.DatabaseEngine.java
public int getRowCount(ResultSet rs) { try {/*from w w w . j a v a 2 s. c o m*/ // int curRow = rs.getRow(); rs.last(); int lastRow = rs.getRow(); rs.first(); // TODO: Set the row??? return lastRow; } catch (Exception e) { return 0; } }
From source file:com.snowy.data.java
public int startGame(String requestor, String requested, int requestId) { int i = 0;/* w w w . j a v a2 s . com*/ try { PreparedStatement pss = con.prepareStatement( "insert into game(p1Id,p2Id,LastMoveBy,fromRequest,LastKnownState,MoveOrder) values((select user_id from users where Username = ?),(select user_id from users where Username=?),?,?,?,?)"); if (new Random().nextInt(100) > 50) { pss.setString(1, requestor); pss.setString(2, requested); pss.setInt(3, this.getUserIdFromUsername(requestor)); } else { pss.setString(1, requested); pss.setString(2, requestor); pss.setInt(3, this.getUserIdFromUsername(requested)); } pss.setInt(4, requestId); String emptyBoard = ""; for (int b = 0; b < 42; b++) { emptyBoard += 0; } pss.setString(5, emptyBoard); pss.setString(6, emptyBoard); if (this.gameCreated(requestId) == false) { //Logger.getLogger(data.class.getName()).info("susposedly "+this.gameCreated(requestId)); if (pss.executeUpdate() > 0) { //Logger.getLogger(data.class.getName()).info("susposedly true"); pss = con.prepareStatement("select GameId from game where fromRequest =?"); pss.setInt(1, requestId); ResultSet rs = pss.executeQuery(); rs.last(); //Logger.getLogger(data.class.getName()).info("susposedly "+rs.getRow()); i = rs.getInt("GameId"); //Logger.getLogger(data.class.getName()).info("susposedly "+i); PreparedStatement ps = con.prepareStatement("select GameId from gamerequest where RequestId=?"); ps.setInt(1, requestId); rs = ps.executeQuery(); rs.last(); if (rs.getInt("GameId") == 0) { ps = con.prepareStatement("update gamerequest set GameId =? where RequestId=?"); ps.setInt(1, i); ps.setInt(2, requestId); ps.executeUpdate(); } //ps.close(); //rs.close(); //con.close(); } else { Logger.getLogger(data.class.getName()).info("susposedly false"); } } else { pss = con.prepareStatement("select GameId from gamerequest where RequestId=?"); pss.setInt(1, requestId); ResultSet rs = pss.executeQuery(); rs.last(); i = rs.getInt("GameId"); //rs.close(); } //pss.close(); } catch (SQLException ex) { Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex); } return i; }
From source file:com.snowy.data.java
public java.sql.Timestamp getCurrentSqlTimestamp() { java.sql.Timestamp dd = null; try {// ww w. ja v a 2 s .c o m ResultSet rs = con.prepareStatement("select current_timestamp() as timestamp").executeQuery(); rs.last(); dd = rs.getTimestamp("timestamp"); //ps.close(); //rs.close(); } catch (SQLException ex) { Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex); } return dd; }
From source file:com.tascape.reactor.report.MySqlBaseBean.java
public void importJson(JSONObject json) throws NamingException, SQLException { JSONObject sr = json.getJSONObject("suite_result"); String srid = sr.getString(SuiteResult.SUITE_RESULT_ID); LOG.debug("srid {}", srid); try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + SuiteResult.TABLE_NAME + " WHERE " + SuiteResult.SUITE_RESULT_ID + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid);/*from w w w .j a v a 2s.c om*/ ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); if (rs.first()) { LOG.debug("already imported {}", srid); return; } rs.moveToInsertRow(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); rs.updateObject(cn, sr.opt(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); LOG.debug("sr imported"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + SuiteProperty.TABLE_NAME + " WHERE " + SuiteProperty.SUITE_RESULT_ID + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); JSONArray sps = sr.getJSONArray("suite_properties"); int len = sps.length(); for (int i = 0; i < len; i++) { rs.moveToInsertRow(); JSONObject tr = sps.getJSONObject(i); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); if (SuiteProperty.SUITE_PROPERTY_ID.equals(cn)) { continue; } rs.updateObject(cn, tr.get(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } LOG.debug("sps imported"); } JSONArray trs = sr.getJSONArray("case_results"); int len = trs.length(); try (Connection conn = this.getConnection()) { String sql = String.format("SELECT * FROM %s WHERE %s=? AND %s=? AND %s=? AND %s=? AND %s=?;", TaskCase.TABLE_NAME, TaskCase.SUITE_CLASS, TaskCase.CASE_CLASS, TaskCase.CASE_METHOD, TaskCase.CASE_DATA_INFO, TaskCase.CASE_DATA); PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setMaxRows(1); for (int i = 0; i < len; i++) { JSONObject tr = trs.getJSONObject(i); stmt.setString(1, tr.getString(TaskCase.SUITE_CLASS)); stmt.setString(2, tr.getString(TaskCase.CASE_CLASS)); stmt.setString(3, tr.getString(TaskCase.CASE_METHOD)); stmt.setString(4, tr.getString(TaskCase.CASE_DATA_INFO)); stmt.setString(5, tr.getString(TaskCase.CASE_DATA)); ResultSet rs = stmt.executeQuery(); if (!rs.first()) { rs.moveToInsertRow(); rs.updateString(TaskCase.SUITE_CLASS, tr.getString(TaskCase.SUITE_CLASS)); rs.updateString(TaskCase.CASE_CLASS, tr.getString(TaskCase.CASE_CLASS)); rs.updateString(TaskCase.CASE_METHOD, tr.getString(TaskCase.CASE_METHOD)); rs.updateString(TaskCase.CASE_DATA_INFO, tr.getString(TaskCase.CASE_DATA_INFO)); rs.updateString(TaskCase.CASE_DATA, tr.getString(TaskCase.CASE_DATA)); rs.insertRow(); rs.last(); rs.updateRow(); rs = stmt.executeQuery(); rs.first(); } tr.put(TaskCase.TASK_CASE_ID, rs.getLong(TaskCase.TASK_CASE_ID)); } LOG.debug("tcid updated"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + CaseResult.TABLE_NAME + " WHERE " + CaseResult.SUITE_RESULT + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < len; i++) { rs.moveToInsertRow(); JSONObject tr = trs.getJSONObject(i); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); rs.updateObject(cn, tr.opt(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } LOG.debug("crs imported"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + CaseResultMetric.TABLE_NAME + ";"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setMaxRows(1); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < len; i++) { JSONArray jarr = trs.getJSONObject(i).optJSONArray("CASE_result_metrics"); if (jarr == null) { continue; } int l = jarr.length(); for (int j = 0; j < l; j++) { JSONObject trm = jarr.getJSONObject(j); rs.moveToInsertRow(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); if (cn.equals(CaseResultMetric.CASE_RESULT_METRIC_ID)) { continue; } rs.updateObject(cn, trm.get(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } } LOG.debug("crms imported"); } }
From source file:com.github.heartsemma.enderauth.Database.java
/**@param uuid (Universally Unique Identifier) * @return A boolean/*from www. j a va2 s .c o m*/ * * <br><Br>Returns true if there is an entry in the User Table with a uuid matching the parameter. * <br>Returns false if there is not. * * @throws SQLException The function uses PreparedStatements to ask about the presence of the UUID in the User Table. * @throws DatabaseException If the returned ResultSet from the SELECT command is completely empty (that is, lacking even the names of the columns in the table), the function throws a DatabaseException.*/ public boolean isInDatabase(byte[] uuid) throws SQLException, DatabaseException { logger.debug("Attempting to determine presence of user " + new String(uuid) + " in the database."); String isInDatabaseCommand = "SELECT * FROM ? WHERE ? = ?"; ArrayList<Object> isInDatabaseVariables = new ArrayList<Object>(); isInDatabaseVariables.add(1, userTableName); isInDatabaseVariables.add(2, userTableIDColumn); isInDatabaseVariables.add(3, uuid); //Command should look something like: SELECT * FROM ea_users WHERE id == uuid ResultSet selection = transact(isInDatabaseCommand, isInDatabaseVariables); logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + "."); logger.debug("Error Checking..."); Preconditions.checkNotNull(selection); //ResultSet Analysis + Error Checking if (selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet. logger.error("EnderAuth attempted to find if there was a uuid matching " + new String(uuid) + " in the database but was unable to run the necessary SQL queries."); logger.error( "There were no rows in the returned table of data after running the MySql 'PreparedStatement'."); throw new DatabaseException("Returned ResultSet in isPresent(String uuid) contained no rows."); } selection.last(); if (selection.getRow() == 1) { //There are no entries in the ResultSet. logger.debug("No entries for user " + new String(uuid) + " were found in the ResultSet."); return false; } else { //There is one or more entries with the matching uuid. logger.debug("User " + new String(uuid) + " was found in the database."); return true; } }
From source file:com.github.heartsemma.enderauth.Database.java
/** * @param uuid (Universally Unique Identifier) * @return The Pre-Shared Key of the user for their TOTP authentication. * //from w w w . j a v a 2s . com * <br><br>Returns the TOTP Pre-Shared Key connected with the specified UUID. * <br>Returns null if unable to retrieve the key (if not found or * * @throws SQLException This function accesses the database via a "SELECT" query. * @throws DatabaseException Thrown if the returned ResultSet contains missing or what should be erroneous data. */ public String getTotpKey(byte[] uuid) throws SQLException, DatabaseException { logger.debug("Attempting to retrieve TOTP PSK for user " + new String(uuid) + "."); String getKeyCommand = "SELECT ? FROM ? WHERE ? == ?"; ArrayList<Object> getKeyVariables = new ArrayList<Object>(); getKeyVariables.add(userTableTotpPSKColumn); getKeyVariables.add(userTableName); getKeyVariables.add(userTableIDColumn); getKeyVariables.add(uuid); ResultSet selection = transact(getKeyCommand, getKeyVariables); logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + "."); //There should be one String in this resultset, but we will check it good because EnderAuth is stronk, EnderAuth is reliable. logger.debug("Error checking..."); Preconditions.checkNotNull(selection); if (!selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet. logger.error("EnderAuth attempted to retrieve " + new String(uuid) + "'s PSK from the database but was unable to find it."); logger.error( "There were no rows in the returned table of data after running the MySql 'PreparedStatement' ."); throw new DatabaseException("getTotpKey()'s PreparedStatement returned a ResultSet that had no data."); } selection.last(); if (selection.getRow() == 1) { //There was no entry for this user. logger.error("EnderAuth attempted to retrieve " + new String(uuid) + "'s PSK from the database but was unable to find it."); logger.error("Does " + new String(uuid) + " have an entry in the " + userTableName + " table?"); //Returns null because we were unable to get the required data. throw new UUIDNotFoundException( "getTotpKey() was unable to find the entry in the database with the specified UUID."); } else if (selection.getRow() == 2) { //There was one entry for this user //If we get to this point, everything looks tight. logger.debug("Successfully retrieved PSK from user " + new String(uuid) + "."); String PSK = selection.getString(userTableTotpPSKColumnIndex); return PSK; } else { //There was more than one entry for this user. logger.error("EnderAuth searched for " + new String(uuid) + "'s PSK and found multiple entries for that user in the database."); logger.error( "This should not have happened and indicates either plugin glitches or malcious database tampering."); throw new DatabaseException("Multiple entries matching the specified UUID were found in the database."); } }
From source file:com.opensoc.enrichment.adapters.geo.GeoMysqlAdapter.java
@SuppressWarnings("unchecked") @Override// w w w.j a va 2 s .c om public JSONObject enrich(String metadata) { ResultSet resultSet = null; try { _LOG.trace("[OpenSOC] Received metadata: " + metadata); InetAddress addr = InetAddress.getByName(metadata); if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress() || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(metadata)) { _LOG.trace("[OpenSOC] Not a remote IP: " + metadata); _LOG.trace("[OpenSOC] Returning enrichment: " + "{}"); return new JSONObject(); } _LOG.trace("[OpenSOC] Is a valid remote IP: " + metadata); statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String locid_query = "select IPTOLOCID(\"" + metadata + "\") as ANS"; resultSet = statement.executeQuery(locid_query); if (resultSet == null) throw new Exception( "Invalid result set for metadata: " + metadata + ". Query run was: " + locid_query); resultSet.last(); int size = resultSet.getRow(); if (size == 0) throw new Exception("No result returned for: " + metadata + ". Query run was: " + locid_query); resultSet.beforeFirst(); resultSet.next(); String locid = null; locid = resultSet.getString("ANS"); if (locid == null) throw new Exception("Invalid location id for: " + metadata + ". Query run was: " + locid_query); String geo_query = "select * from location where locID = " + locid + ";"; resultSet = statement.executeQuery(geo_query); if (resultSet == null) throw new Exception("Invalid result set for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.last(); size = resultSet.getRow(); if (size == 0) throw new Exception("No result id returned for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.beforeFirst(); resultSet.next(); JSONObject jo = new JSONObject(); jo.put("locID", resultSet.getString("locID")); jo.put("country", resultSet.getString("country")); jo.put("city", resultSet.getString("city")); jo.put("postalCode", resultSet.getString("postalCode")); jo.put("latitude", resultSet.getString("latitude")); jo.put("longitude", resultSet.getString("longitude")); jo.put("dmaCode", resultSet.getString("dmaCode")); jo.put("locID", resultSet.getString("locID")); jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude")); _LOG.debug("Returning enrichment: " + jo); return jo; } catch (Exception e) { e.printStackTrace(); _LOG.error("Enrichment failure: " + e); return new JSONObject(); } }