Java Code Examples for java.sql.ResultSet.isBeforeFirst()

The following are Jave code examples for showing how to use isBeforeFirst() of the java.sql.ResultSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: limitjson   File: FlipTableConverters.java   View Source Code Vote up 6 votes
/**
 * Create a table from a {@link ResultSet}.
 */
public static String fromResultSet(ResultSet resultSet) throws SQLException {
    if (resultSet == null) throw new NullPointerException("resultSet == null");
    if (!resultSet.isBeforeFirst()) throw new IllegalStateException("Result set not at first.");

    List<String> headers = new ArrayList<>();
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    int columnCount = resultSetMetaData.getColumnCount();
    for (int column = 0; column < columnCount; column++) {
        headers.add(resultSetMetaData.getColumnName(column + 1));
    }

    List<String[]> data = new ArrayList<>();
    while (resultSet.next()) {
        String[] rowData = new String[columnCount];
        for (int column = 0; column < columnCount; column++) {
            rowData[column] = resultSet.getString(column + 1);
        }
        data.add(rowData);
    }

    String[] headerArray = headers.toArray(new String[headers.size()]);
    String[][] dataArray = data.toArray(new String[data.size()][]);
    return FlipTable.of(headerArray, dataArray);
}
 
Example 2
Project: momo-2   File: MacroObject.java   View Source Code Vote up 6 votes
/**
 * Returns top macro and hits
 * @param guildId
 * @return Object array with index 0: hits 1: macro name 2: userid 3: fallback username
 * @throws NoMacroFoundException
 */
public static Object[] topMacro(String guildId) {
	Connection conn = null;
	PreparedStatement stmt = null;
	ResultSet rs = null;
	try {
		conn = ConnectionPool.getConnection(guildId);
		stmt = conn.prepareStatement("SELECT hits, macro, user_id, user_created FROM `discord_macro` ORDER BY hits DESC LIMIT 1");
		rs = stmt.executeQuery();
		if(!rs.isBeforeFirst())
			return null;
		rs.next();
		return new Object[] {rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)};
	} catch(SQLException e) {
		e.printStackTrace();
	} finally {
		SQLUtils.closeQuietly(rs);
		SQLUtils.closeQuietly(stmt);
		SQLUtils.closeQuietly(conn);
	}
	return null;
}
 
Example 3
Project: Java-Air-Reservation   File: Flight.java   View Source Code Vote up 6 votes
/**
 * Constructor to auto load flight details from db
 *
 * @param flight_no
 */
public Flight(String flight_no) {
    this.conn = DBConnect.connect();
    PreparedStatement pst = null;
    try {
        String sql = "SELECT * FROM `flight` WHERE `flight_no` = ?";
        pst = conn.prepareStatement(sql);
        pst.setString(1, flight_no);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst()) {
            return;
        }
        while (rs.next()) {
            this.flight_no = rs.getString("flight_no");
            this.max_seats = rs.getInt("max_seats");
            this.airline_ID = rs.getString("airline_ID");
            this.active = rs.getBoolean("active");
            this.exist = true;
        }
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
    }
}
 
Example 4
Project: IP1   File: BorrowedBook.java   View Source Code Vote up 6 votes
public BorrowedBookEntity getBorrowedBookDetails(int id) {
    try {
        ResultSet rs = connector.executeSelectStatement("SELECT borrowed_books.id, borrowed_books.date, borrowed_books.return_date, borrowed_books.fee_applied, "
            + "borrowed_books.user_id, borrowed_books.book_id, books.title, books.category, books.author, books.isbn, books.publisher FROM borrowed_books "
            + "INNER JOIN books ON borrowed_books.book_id = books.id WHERE borrowed_books.id LIKE " + id);
        if(rs.isBeforeFirst()) {
            rs.first();
            BorrowedBookEntity entity = new BorrowedBookEntity(rs.getInt("id"), rs.getInt("user_id"), rs.getInt("book_id"), rs.getString("title"), rs.getString("category"), rs.getString("author"),
                rs.getInt("isbn"), rs.getString("publisher"), rs.getDate("date"), rs.getDate("return_date"), rs.getInt("fee_applied"));
            return entity;
        }
        return null;
    } catch (SQLException ex) {
        Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 5
Project: AdamantineShield   File: DataCache.java   View Source Code Vote up 6 votes
public Integer getDataId(Connection c, String data) throws SQLException {
	if (cache.containsKey(data))
		return cache.get(data);
	
	ResultSet r = c.createStatement().executeQuery("SELECT id FROM " + tableName + " WHERE " + dataRowName + " = '" + data + "'");
	if (!r.isBeforeFirst()) {
		c.createStatement().executeUpdate("INSERT INTO " + tableName + " (" + dataRowName + ") VALUES ('" + data + "');");
		r = c.createStatement().executeQuery("SELECT id FROM " + tableName + " WHERE " + dataRowName + " = '" + data + "'");
	}
	r.next();
	
	int result = r.getInt("id");
	r.close();
	
	cache.put(data, result);
	return result;
}
 
Example 6
Project: momo-2   File: MacroObject.java   View Source Code Vote up 5 votes
/**
 * Search for a macro by name given the guild ID
 * @param name Name to wildcard
 * @param guildId GuildID to search in
 * @return Null if no results, populated string array of macro names if results
 */
public static String[] searchForName(String name, String guildId) {
	Connection conn = null;
	PreparedStatement stmt = null;
	ResultSet rs = null;
	ArrayList<String> toReturn = new ArrayList<String>(10);
	try {
		conn = ConnectionPool.getConnection(guildId);
		String sql = "SELECT macro FROM `discord_macro` WHERE macro LIKE ?";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, "%" + name + "%");
		rs = stmt.executeQuery();
		if(!rs.isBeforeFirst())
			return null;
		while(rs.next()) {
			toReturn.add(rs.getString(1));
		}
		return toReturn.toArray(new String[0]);
	} catch(SQLException e) {
		e.printStackTrace();
		return null;
	} finally {
		SQLUtils.closeQuietly(rs);
		SQLUtils.closeQuietly(stmt);
		SQLUtils.closeQuietly(conn);
	}

}
 
Example 7
Project: momo-2   File: MacroObject.java   View Source Code Vote up 5 votes
/**
 * Get and return a macro for given macroName
 * If found, increment the hits
 * @param name Macro name to search for
 * @param guildId Guild ID to search in
 * @return Macro if found
 * @throws NoMacroFoundException if no macro is found
 */
public static MacroObject forName(String name, String guildId, boolean hit) throws IllegalArgumentException {
	Connection conn = null;
	PreparedStatement stmt = null;
	ResultSet rs = null;
	try {
		conn = ConnectionPool.getConnection(guildId);
		String sql = "SELECT user_created, date_created, content, hits, user_id FROM `discord_macro` WHERE macro = ?";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, name.toLowerCase());
		rs = stmt.executeQuery();
		if(!rs.isBeforeFirst()) {
			throw new IllegalArgumentException("No macro found for " + name);
		}
		rs.next();
		if(hit) {
			sql = "UPDATE `discord_macro` SET hits = hits+1 WHERE macro = ?";
			PreparedStatement stmt2 = conn.prepareStatement(sql);
			stmt2.setString(1, name.toLowerCase());
			stmt2.execute();
			SQLUtils.closeQuietly(stmt2);
		}
		return new MacroObject(rs.getString(1), name, rs.getString(3), rs.getInt(4), rs.getString(5),
				guildId, LocalDate.parse(rs.getObject(2).toString()));
	} catch(SQLException e) {
		e.printStackTrace();
	} finally {
		SQLUtils.closeQuietly(rs);
		SQLUtils.closeQuietly(stmt);
		SQLUtils.closeQuietly(conn);
	}
	return null;
}
 
Example 8
Project: Java-Air-Reservation   File: Tickets.java   View Source Code Vote up 5 votes
/**
 * 
 * @param psNo
 * @param Plegno 
 */
public Tickets(int psNo, int Plegno) {
    conn = DBConnect.connect();
    PreparedStatement pst = null;
    try {
        String sql = "SELECT * FROM `tickets` WHERE `seat_no`=? AND `leg_no`=?";
        pst = conn.prepareStatement(sql);
        pst.setInt(1, psNo);
        pst.setInt(2, Plegno);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst()) {
            return;
        }
        while (rs.next()) {
            this.seat_no = rs.getInt("seat_no");
            this.pass_no = rs.getString("pass_no");
            this.leg_no = rs.getInt("leg_no");
            this.class_ = rs.getInt("class");
            this.exist = true;
        }

    } catch (SQLException e) {
        System.out.println("Error:" + e);

    }
}
 
Example 9
Project: Java-Air-Reservation   File: Admin.java   View Source Code Vote up 5 votes
/**
 * constructor with the id
 * @param adminid : admin id
 */
public  Admin(int adminid){
    conn = DBConnect.connect();
    PreparedStatement pst;
    try {
        String sql = "SELECT * FROM `admin` WHERE `admin_id` = ?";
        pst=conn.prepareStatement(sql);
        pst.setInt(1,adminid);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst() ) {     
            return;
        } 
        while (rs.next()) {
                this.admin_id =rs.getInt("admin_id");
                this.password = rs.getString("password");
                this.user_name = rs.getString("user_name");
                this.admin_level = rs.getInt("admin_level");
                this.name = rs.getString("name");
                this.exist = true;
        }
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
        System.out.println(e.getErrorCode());
    }
}
 
Example 10
Project: Java-Air-Reservation   File: Admin.java   View Source Code Vote up 5 votes
/**
 * constructor with the id
 * @param username : user name of admin
 * @param pass : admin password 
 * @return  : boolian login details validity
 */
public boolean adminLogin(String username,String pass){
    conn = DBConnect.connect();
    PreparedStatement pst;
    try {
        String sql = "SELECT * FROM `admin` WHERE `user_name` = ? AND `password` = ?";
        pst=conn.prepareStatement(sql);
        pst.setString(1,username);
        pst.setString(2, pass);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst() ) {     
            return false;
        } 
        while (rs.next()) {
                this.admin_id =rs.getInt("admin_id");
                this.password = rs.getString("password");
                this.user_name = rs.getString("user_name");
                this.admin_level = rs.getInt("admin_level");
                this.name = rs.getString("name");
                this.exist = true;
                return true;
        }
        return false;
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
        System.out.println(e.getErrorCode());
        return false;
    }
}
 
Example 11
Project: Java-Air-Reservation   File: FlightLeg.java   View Source Code Vote up 5 votes
/**
 * Constructor to auto load flight leg from db
 * @param leg_no : primary key of Flight leg
 */
public FlightLeg(int leg_no)
{
  this.conn = DBConnect.connect(); 
  PreparedStatement pst = null;
    try {
        String sql = "SELECT * FROM `flight_leg` WHERE `leg_no` = ?";
        pst=conn.prepareStatement(sql);
        pst.setInt(1,leg_no);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst() ) {     
            return;
        } 
        while (rs.next()) {
            this.leg_no = rs.getInt("leg_no");
            this.leg_type = rs.getString("leg_type");
            this.from_aID = rs.getString("from_aID");
            this.to_aID = rs.getString("to_aID");
            this.departure_time = rs.getTimestamp("departure_time");
            this.arival_time = rs.getTimestamp("arival_time");
            this.flight_no = rs.getString("flight_no");
            this.exist = true;
        }
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
    }
}
 
Example 12
Project: Java-Air-Reservation   File: Passenger.java   View Source Code Vote up 5 votes
/**
 * constructor with the id
 * @param passNo : passport number 
 */
public  Passenger(String passNo){
    conn = DBConnect.connect();
    PreparedStatement pst;
    try {
        String sql = "SELECT * FROM `passenger` WHERE `pass_no`=?";
        pst=conn.prepareStatement(sql);
        pst.setString(1,passNo);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst() ) {     
            return;
        } 
        while (rs.next()) {
                this.tel = rs.getString("tel");
                this.paddress = rs.getString("paddress");
                this.fname = rs.getString("fname");
                this.lname = rs.getString("lname");
                this.pass_no = rs.getString("pass_no");
                this.password = rs.getString("password");
                this.dob = rs.getDate("dob");
                this.active  = rs.getBoolean("active");
                this.exist = true;
        }
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
        System.out.println(e.getErrorCode());
    }
}
 
Example 13
Project: momo-2   File: MacroObject.java   View Source Code Vote up 5 votes
/**
 * Search for macros by user and given guild
 * @param userId UserID to search for
 * @param guildId GuildID to search in
 * @return Null if no results, populated string array of macro names if results
 */
public static String[] searchByUser(String userId, String guildId) {
	Connection conn = null;
	PreparedStatement stmt = null;
	ResultSet rs = null;
	ArrayList<String> toReturn = new ArrayList<String>(10);
	try {
		conn = ConnectionPool.getConnection(guildId);
		String sql = "SELECT macro FROM `discord_macro` WHERE user_id = ?";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, userId);
		rs = stmt.executeQuery();
		if(!rs.isBeforeFirst())
			return null;
		while(rs.next()) {
			toReturn.add(rs.getString(1));
		}
		return toReturn.toArray(new String[0]);
	} catch(SQLException e) {
		e.printStackTrace();
		return null;
	} finally {
		SQLUtils.closeQuietly(rs);
		SQLUtils.closeQuietly(stmt);
		SQLUtils.closeQuietly(conn);
	}
}
 
Example 14
Project: Java-Air-Reservation   File: Airport.java   View Source Code Vote up 5 votes
/**
 * constructor with an ID
 */
public Airport(String aid){
    conn = DBConnect.connect();
    PreparedStatement pst = null;
    try {
        String sql = "SELECT * FROM `airport` WHERE `airportID`=?";
        pst = conn.prepareStatement(sql);
        pst.setString(1, aid);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst() ) {     
            return;
        }
        while(rs.next()){
            this.airportID = rs.getString("airportID");
            this.name = rs.getString("name");
            this.city = rs.getString("city");
            this.apstate = rs.getString("apstate");
            this.country = rs.getString("country");
            this.active = rs.getBoolean("active");
            this.exist = true;
        }
        
    } catch (SQLException e) {
        System.out.println("Error:"+e);
        
    }
}
 
Example 15
Project: IP1   File: RequestedBook.java   View Source Code Vote up 5 votes
public RequestedBookEntity getRequestedBookDetails(int id) {
    try {
        ResultSet rs = connector.executeSelectStatement("SELECT requested_books.id, requested_books.date, requested_books.user_id, requested_books.book_id, "
            + "books.title, books.category, books.author, books.isbn, books.publisher FROM requested_books INNER JOIN "
            + "books ON requested_books.book_id = books.id WHERE requested_books.id LIKE " + id);
        if(rs.isBeforeFirst()) {
            rs.next();
            return new RequestedBookEntity(rs.getInt("id"), rs.getInt("user_id"), rs.getInt("book_id"), rs.getString("title"), rs.getString("category"), rs.getString("author"),
                rs.getInt("isbn"), rs.getString("publisher"), rs.getDate("date"));
        }
    } catch (SQLException ex) {
        Logger.getLogger(RequestedBook.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 16
Project: IP1   File: User.java   View Source Code Vote up 5 votes
public boolean isLoginCorrect(String email, String password) {
    try {
        ResultSet rs = connector.executeSelectStatement("SELECT password FROM users WHERE users.email LIKE '" + email + "'");
        if(rs.isBeforeFirst()) {
            rs.first();
            return rs.getString("password").equals(password);
        }
        return false;
    } catch (SQLException ex) {
        Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}
 
Example 17
Project: IP1   File: User.java   View Source Code Vote up 5 votes
public double getUserBalance(int userId) {
    ResultSet rs = connector.executeSelectStatement("SELECT balance FROM users WHERE id LIKE " + userId);
    try {
        if(rs.isBeforeFirst()) {
            rs.first();
            return rs.getDouble("balance");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
    }
    return 0;
}
 
Example 18
Project: IP1   File: Book.java   View Source Code Vote up 5 votes
public int getBookQuantity(int bookId) {
    ResultSet rs = connector.executeSelectStatement("SELECT quantity FROM books WHERE id LIKE " + bookId);
    try {
        if(rs.isBeforeFirst()) {
            rs.first();
            return rs.getInt("quantity");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
    }
    return 0;
}
 
Example 19
Project: open-rmbt   File: OpenTestResource.java   View Source Code Vote up 4 votes
/**
 * Gets all signal measurements from a test
 *
 * @param testUID  the test uid
 * @param testTime the begin of the test
 * @throws SQLException
 */
public SignalGraph(long testUID, UUID openTestUuid, long testTime, java.sql.Connection conn) throws SQLException {
    PreparedStatement psSignal = conn.prepareStatement("SELECT test_id, nt.name network_type, nt.group_name cat_technology, signal_strength, lte_rsrp, lte_rsrq, wifi_rssi, time "
            + "FROM signal "
            + "JOIN network_type nt "
            + "ON nt.uid = network_type_id "
            + "WHERE test_id = ? "
            + "ORDER BY time;");
    psSignal.setLong(1, testUID);

    ResultSet rsSignal = psSignal.executeQuery();

    //if there are no results -> try using the new radio-tables that may be available for some measurements
    if (!rsSignal.isBeforeFirst()) {
        psSignal = conn.prepareStatement("SELECT radio_cell.open_test_uuid, nt.name network_type, technology cat_technology, signal_strength, lte_rsrp, lte_rsrq, signal_strength wifi_rssi, time " +
                "FROM radio_cell " +
                "JOIN radio_signal ON radio_signal.cell_uuid = radio_cell.uuid " +
                "JOIN network_type nt ON nt.uid = network_type_id " +
                "WHERE radio_cell.open_test_uuid = ? " +
                "AND radio_cell.active = TRUE " +
                "  ORDER BY radio_signal.time;");
        psSignal.setObject(1, openTestUuid);

        rsSignal = psSignal.executeQuery();
    }

    boolean first = true;
    SignalGraphItem item = null;
    while (rsSignal.next()) {
        long timeElapsed = rsSignal.getTimestamp("time").getTime() - testTime;
        //there could be measurements taken before a test started
        //in this case, only return the last one
        if (first && timeElapsed > 0 && item != null) {
            this.signalList.add(item);
            first = false;
        }

        //ignore measurements after a threshold of one minute
        if (timeElapsed > MAX_TIME)
            break;


        int signalStrength = rsSignal.getInt("signal_strength");
        int lteRsrp = rsSignal.getInt("lte_rsrp");
        int lteRsrq = rsSignal.getInt("lte_rsrq");
        if (signalStrength == 0)
            signalStrength = rsSignal.getInt("wifi_rssi");

        if (signalStrength > LOWER_BOUND)
            item = new SignalGraphItem(Math.max(timeElapsed, 0), rsSignal.getString("network_type"), signalStrength, lteRsrp, lteRsrq, rsSignal.getString("cat_technology"));


        //put 5-let in the array if it is not the first one
        if (!first || rsSignal.isLast()) {
            if (timeElapsed < 0) {
                item.timeElapsed = 1000;
            }
            this.signalList.add(item);
        }
    }

    rsSignal.close();
    psSignal.close();
}
 
Example 20
Project: lams   File: Loader.java   View Source Code Vote up 4 votes
/**
 * Loads a single logical row from the result set moving forward.  This is the
 * processing used from the ScrollableResults where there were collection fetches
 * encountered; thus a single logical row may have multiple rows in the underlying
 * result set.
 *
 * @param resultSet The result set from which to do the load.
 * @param session The session from which the request originated.
 * @param queryParameters The query parameters specified by the user.
 * @param returnProxies Should proxies be generated
 * @return The loaded "row".
 * @throws HibernateException
 */
public Object loadSequentialRowsForward(
		final ResultSet resultSet,
		final SessionImplementor session,
		final QueryParameters queryParameters,
		final boolean returnProxies) throws HibernateException {

	// note that for sequential scrolling, we make the assumption that
	// the first persister element is the "root entity"

	try {
		if ( resultSet.isAfterLast() ) {
			// don't even bother trying to read further
			return null;
		}

		if ( resultSet.isBeforeFirst() ) {
			resultSet.next();
		}

		// We call getKeyFromResultSet() here so that we can know the
		// key value upon which to perform the breaking logic.  However,
		// it is also then called from getRowFromResultSet() which is certainly
		// not the most efficient.  But the call here is needed, and there
		// currently is no other way without refactoring of the doQuery()/getRowFromResultSet()
		// methods
		final EntityKey currentKey = getKeyFromResultSet(
				0,
				getEntityPersisters()[0],
				null,
				resultSet,
				session
			);

		return sequentialLoad( resultSet, session, queryParameters, returnProxies, currentKey );
	}
	catch ( SQLException sqle ) {
		throw factory.getSQLExceptionHelper().convert(
				sqle,
				"could not perform sequential read of results (forward)",
				getSQLString()
			);
	}
}