How to get the "x highest value" in mysql - java

I am still a beginner in Java and stackoverflow.
I coded a plugin for a minecraft server in java, using mysql for a stats system (Kills deaths points)
I want to know, how i can get the player with the highest amount of "Points", so i like to get the "Playername" where "Points" is the highest.
I also would like to get the 2nd highest, 3rd highest etc.
I used prepared statements like:
public static int getPoints(String Playername) {
int Points = 0;
try {
PreparedStatement st = con
.prepareStatement("SELECT Points FROM FFA WHERE UUID = '"
+ PlayerUtil.getUUID(Playername) + "'");
ResultSet rs = st.executeQuery();
if (rs.next()) {
Points = rs.getInt("Points");
} else {
Points = 0;
}
} catch (SQLException e) {
e.printStackTrace();
}
return Points;
}
If you are able to help me, that would be extremely nice!
Thanks for your time!
PS:
My SQL structure:
Playername varchar(64)
UUID varchar(64)
Kills int
Deaths int
Points int

You can use the following statement to do that:
select playername from FFA order by points desc limit 10;
That will return the top 10 players
Or you could do something like
select playername from FFA where points >= 1337 order by points DESC;
Then you can go through every entry calling rs.next() in a loop. First fetch with rs.next() will get you the player with more points because you used order by.
So the code would look like this:
public static String getTopPlayer() {
int limit = 10;
try {
preparedstatement st = con
.preparestatement("select * from FF order by points desc limit "
+ limit);
resultset rs = st.executequery();
if (rs.next()) {
name = rs.getString("playername");
//if rs.next() rs.getString("playername"); <-- returns second
//if rs.next(); rs.getString("playername"); <-- returns third
} else {
name = null;
}
} catch (sqlexception e) {
e.printstacktrace();
}
return name;

You can try something like this in SQL :
select playername from FFA where points=(select max(points) from FFA);
This query can return more than one row...

Related

want to return an rs.getInt() value in my database

I want to return an rs.getInt() value in this code snippet in my database. I really need it because I have to display the "User's score" in my Java Swing Simple Quiz Program, but it will always return 0 instead of what I want.
public int score() {
kon = koneksi.koneksiDb();
try {
st = kon.createStatement();
formLogin fl = new formLogin();
String sql = "SELECT score FROM user WHERE username = '" + fl.usr + "'";
rs = st.executeQuery(sql);
if (rs.next())
return rs.getInt(5);
} catch(SQLException e) {
JOptionPane.showMessageDialog(null, "Maaf, terjadi kesalahan.");
}
return 0;
}
My "score" column in the database is an integer.
Thanks to #DanielBarbardian and #deHaar in the comments. I tried return rs.getInt("score"); and it works. It'll return the score from the right column and display the right user's score.

Can I use setMaxRows() with try-with-resouces?

I am attempting to write a method that selects 2 entries into an employee database and removes them (Based on a salary field), I am currently using a counter to accomplish this, however I tried using setMaxRows() so my result set would only have two entries, thus eliminating the need for the counter. I am using try-with-resources to create my statement and that seems to be causing an issue.
public void downSize(Connection con) {
String sql = "SELECT * FROM " + schemaName + "."+tableName+" WHERE EMPLOYEE_SALARY>200000";
try (
PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = statement.executeQuery();
)
{
int counter = 0;
System.out.println("Now pruning workforce...");
while(rs.next() && counter<2) {
String name = rs.getString("EMPLOYEE_NAME");
rs.deleteRow();
counter++;
System.out.println(name+" was laid off.");
}
} catch(Exception e) {
e.printStackTrace();
System.out.print("Sql exception happened");
}
}

Pull string from sql to java

I am trying to pull a first name and last name from a table in my SQL database. The queries work fine in SQL without the "as First" part and I know the db connection is fine since it works in every other part of the code.
The error I receive is that table "First" does not exist, but it should be looking at firstName and lastName for the table names, not First and Last.
Its inside of a for loop with "i", but those values are correct, playerid = i exists.
try {
String query2 = " SELECT firstName as First from player "
+ "WHERE playerid = ?";
PreparedStatement st2 = db.conn.prepareStatement(query);
st2.setInt(1, i);
ResultSet rs2 = st2.executeQuery();
if (rs2.next()) {
setFirstName(rs2.getString("First"));
}
String query3 = " SELECT lastName as Last from player "
+ "WHERE playerid = ?";
PreparedStatement st3 = db.conn.prepareStatement(query);
st3.setInt(1, i);
ResultSet rs3 = st3.executeQuery();
if (rs3.next()) {
setLastName(rs3.getString("Last"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
Change your code into something like this:
PreparedStatement ps = null;
try {
ps = db.conn.prepareStatement("SELECT firstName, lastName from player "
+ "WHERE playerid = ?");
for (int i = 0; i < MAX_PLAYERS /*<- or what is the loop condition?*/; i++) {
ps.setInt(1, i);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// should these methods really be called within a loop?
setFirstName(rs.getString("firstName"));
setLastName(rs.getString("lastName"));
}
rs.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (ps != null) {
ps.close();
}
}
Some considerations:
When you're using a PreparedStatement within a loop, you should create the statement once, outside of the loop and then only re-assign the bind variable(s) during each iteration.
You should minimize the number of queries you run against the DB; in your case you should select both the first and last name column in a single query.
It is important to close the resources you open up (the PreparedStatement in this case). My example shows how this is usually done (in the finally block) pre Java 7. Use the try-with-resources statement if you're using a newer Java version.

Java ResultSet returning all records after the first correct record is found from MySQL Query

Ok, so for example my table would look like:
┌──────┬────────┬─────────────┬───────────┐
│UserID│Username│CurrentLeague│TotalPoints│
├──────┼────────┼─────────────┼───────────┤
│1 │Elliot │randomLeague │15 │
├──────┼────────┼─────────────┼───────────┤
│2 │Callum │randomLeague │20 │
├──────┼────────┼─────────────┼───────────┤
│3 │Rory │testLeague │17 │
├──────┼────────┼─────────────┼───────────┤
│4 │Admin │NULL │0 │
├──────┼────────┼─────────────┼───────────┤
│5 │Steve │randomLeague │21 │
└──────┴────────┴─────────────┴───────────┘
And here is my code in my Java project for the class that I'm using here.
public int getLeaguePosition(String username)
{
try
{
int leaguePosition = 0;
String leagueName = getLeague(username);
System.out.println("League Name: " + leagueName);
ArrayList<SortingUser> sortingUser = new ArrayList<SortingUser>();
String query = "SELECT * FROM Users WHERE CurrentLeague = ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, leagueName);
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
String retrievedUsername = resultSet.getString("Username");
System.out.println(retrievedUsername);
SortingUser retrievedUser = new SortingUser(retrievedUsername);
sortingUser.add(retrievedUser);
}
Collections.sort(sortingUser);
for(int i = 0; i < sortingUser.size(); i++)
{
SortingUser retrievedSortingUser = sortingUser.get(i);
String retrievedUsername = retrievedSortingUser.getUsername();
if(retrievedUsername.contains(username) && username.contains(retrievedUsername))
{
leaguePosition = i + 1;
System.out.println("League Position for " + username.toUpperCase() + " is " + leaguePosition);
return leaguePosition;
}
}
}
catch(Exception e)
{
System.out.println("Couldn't get league position for: " + username);
e.printStackTrace();
}
return 0;
}
and if I gave it "Rory" as the username it would return the records with ID 3, 4 and 5 rather than just 3 when calculating the position.
Why does it do this? I'm fairly sure my code is correct because when I copy that exact SQL query into phpMyAdmin it works perfectly.
I am not sure what you were trying to do there with the SortingUser, but I'd go with much simpler code, and let SQL do its own sorting. It's usually very efficient at that, especially if you have the proper indexes on the table.
public int getLeaguePosition(String username)
{
try
{
String leagueName = getLeague(username);
System.out.println("League Name: " + leagueName);
// This is returning all the users in the same league sorted by descending points.
String query = "SELECT * FROM Users WHERE CurrentLeague = ? ORDER BY TotalPoints DESC";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, leagueName);
resultSet = preparedStatement.executeQuery();
int leaguePosition = 0;
while(resultSet.next())
{
// Since the result set is already sorted, the first player has the most points, so his
// leaguePosition is one. The second has the next best number of points, so his position
// is two, and so on. So we keep the leaguePosition var based on the number of the row.
leaguePosition++;
// And if the user name retrieved actually matches the one that we passed, then this is
// his league position.
String retrievedUsername = resultSet.getString("Username");
if ( retrievedUsername.equals( username ) ) {
break;
}
}
resultSet.close();
return leaguePosition;
}
catch(Exception e)
{
System.out.println("Couldn't get league position for: " + username);
e.printStackTrace();
}
return 0;
}
Have you implemented Comparable interface in SortingUser class?
Collections.sort() will not sort the objects, if you haven't implemented Comparable in your class.
for simple example check this out!!

User ranking with Java and SQL

I am trying to determine the ranking of a user by their score from an external database using Java and SQL. Here's what I have so far:
public int findRanking(User user){
int count =0;
if (c == null) {
c = getConnection();
}
try{
Statement s =c.createStatement();
String query="SELECT * FROM USERS ORDER BY SCORE DESC";
ResultSet rs = s.executeQuery(query);
while(rs.next()){
..
}
}catch (Exception e) {
System.out.println("exception: " + e);
}
I'm not sure how to operate the while loop to return the ranking. If anybody has any suggestions I would really appreciate it.
First off, the method you provided has a syntax error, you close the function body after c=getConnection();
You should read the javadocs for resultset here.
You can read your score by doing:
if (rs.next()) {
score = rs.getInt("SCORE");
}
no need for a while loop, since you only want the score of one user :)
Also, this method does not return the score of a given user, it returns the highest score of all users. You should modify your query to do something along the lines of:
String query="SELECT * FROM USERS WHERE USERID = " + user.getId() + "ORDER BY SCORE DESC";
Do you see why?
Try following:
SET #ranking := 0;
SELECT #ranking := #ranking+1 as ranking, * FROM (SELECT * FROM USERS ORDER BY SCORE DESC)
With this you will not need a while loop to determine ranking.
recommendation: instead of *, list the fields you are expecting -- query is faster then.
for a single user:
SET #ranking := 0;
SELECT * from (SELECT #ranking := #ranking+1 as ranking, * FROM (SELECT * FROM USERS ORDER BY SCORE DESC) U) W where userId='89'
Final code. Thanks a lot guys for your help:
public int findRanking(String username){
int rank =1;
if (c == null) {
c = getConnection();}
try{
Statement s =c.createStatement();
String query="SELECT * FROM USERS ORDER BY SCORE DESC";
ResultSet rs = s.executeQuery(query);
while(rs.next()){
String current=rs.getString("USERNAME");
if(username.equals(current)){
return rank;
}
else{
rank++;
}
}
}catch (Exception e) {
System.out.println("exception: " + e);
}
return rank;
}

Categories