Java/MySQL – 如何从特定行检索数据

huangapple 未分类评论46阅读模式
英文:

Java/MySQL - How to retrieve data from specific row

问题

我确实找不到这个问题的解决方案:

这里我有两个结果集(ResultSets),一个始终显示我的数据库中存储的项目数量,另一个从中检索所有数据。
我想生成一个随机数,然后基于数据库中的行号/ID生成一个随机项目。由于我相当新手,不确定这是否是一种有效的方法。每次检索所有数据然后进行迭代,看起来并不是很清晰。特别是如果我有像1000个项目,而随机生成的数字是999。

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

尝试在最后一行调用列名itemname。然而,我只是不能找到一个好的解决方案来解决这个问题。非常感谢任何帮助,因为我对数据库相当新手。

谢谢

编辑:这是我现在尝试的,但是没有任何输出

对于以下代码也是一样的:

ResultSet numberOfItemsInDataBase = stmt.executeQuery("SELECT count(*) FROM items;");
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);
}
英文:

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);
    			}

答案1

得分: 0

使用ORDER BY RAND()将结果限制为1。这样可以避免您必须查询计数,然后最终在结果集中迭代,直到找到随机条目。

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

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);
    }
}

答案2

得分: 0

如果您只需要表中的随机一行数据,您可以使用纯SQL和函数 RAND() 来实现:

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

如果您想要使用生成的随机数,可以在 SQL 语句的 OFFSET 子句中使用它:

ResultSet numberOfItemsInDataBase = stmt.executeQuery("SELECT count(*) FROM items;");
// 上述查询将仅返回 1 行结果
numberOfItemsInDataBase.next(); 
// 这将返回一个介于 0 和行数减 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));
}
英文:

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));
}

答案3

得分: 0

你可以使用limit函数来获取项目。

LIMIT子句可用于限制SELECT语句返回的行数。LIMIT接受一个或两个数字参数,这两个参数必须都是非负整数常量(在使用预处理语句时除外)。

当有两个参数时,第一个参数指定要返回的第一行的偏移量,第二个参数指定要返回的最大行数。初始行的偏移量是0(而不是1)。因此,在您的情况下,偏移量可以是随机生成的id减去1,最大行数为1:

select * from items LIMIT {id-1},1;  # 检索行(id-1
英文:

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)

huangapple
  • 本文由 发表于 2020年7月26日 21:41:33
  • 转载请务必保留本文链接:https://java.coder-hub.com/63100935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定