简体   繁体   中英

Java/MySQL - How to retrieve data from specific row

I really can't find a solution for this problem:

Here I have two ResultSets, one which always shows me the number of items stored in my database and one that retrieves all the data from it. I would like to generate a random number and then generate a random item based on the row number/id in my database. Since I'm fairly new I'm not sure if this is an efficient approach. It doesn't look very clean to retrieve all the data and then iterate over it every time. Especially if I had like 1000 items and the randomly generated number is 999.

PreparedStatement randomSelection = con.prepareStatement("SELECT * FROM items ORDER BY RAND() LIMIT 1"); {
                String name = ((ResultSet) randomSelection).getString(2);
            
            System.out.println(name);
            }

Tried calling the column itemname with the last line. However I just can't look for a good solution for this problem. Would highly appreciate any help since I'm fairly new to databases.

Thank you

EDIT: This is what I tried now and there is no output somehow

Same for

ResultSet numberOfItemsInDataBase = stmt.executeQuery("SELECT count(*) FROM items;");
                // this will return a number between 0 and the number of rows - 1
                int id = new Random().nextInt(numberOfItemsInDataBase.getInt(1));
                ResultSet itemsInDataBase = stmt.executeQuery("select * from items order by id limit 1 offset " + id);
                if (itemsInDataBase.next()) {
                    String item = itemsInDataBase.getString(2);
                    System.out.println(item);
                }

Use ORDER BY RAND() and limit the result to 1. This circumvents you having to query for the count and then ultimately iterate through the ResultSet until you find the random entry.

try (ResultSet randomSelection = connection
        .preparedStatement("SELECT * FROM items ORDER BY RAND() LIMIT 1")) {
    if (randomSelection.next()) {
        String name = randomSelection.getString(2);
    }
}

If you just need a random row of the table then you can do it with plain SQL with the function RAND() :

ResultSet itemsInDataBase = stmt.executeQuery("select * from items order by rand() limit 1");
if (itemsInDataBase.next()) {
    item = new Item(itemsInDataBase.getString(2));
}

If you want to use the generated random number, then use it in the OFFSET clause of the sql statement:

ResultSet numberOfItemsInDataBase = stmt.executeQuery("SELECT count(*) FROM items;");
// the above query will return exactly 1 row
numberOfItemsInDataBase.next(); 
// this will return a number between 0 and the number of rows - 1
int id = new Random().nextInt(numberOfItemsInDataBase.getInt(1)); 
ResultSet itemsInDataBase = stmt.executeQuery("select * from items order by id limit 1 offset " + id);
if (itemsInDataBase.next()) {
    item = new Item(itemsInDataBase.getString(2));
}

You can use the limit function to get the item.

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1). So in your case the offset can be the the random generated id minus one and maximum number of rows is 1:

select * from items LIMIT {id-1},1;  # Retrieve row (id-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM