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



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

这里我有两个ResultSet,一个总是显示存储在数据库中的项数,另一个从数据库中检索所有数据。我想生成一个随机数,然后根据数据库中的行号/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;");
// 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);
}

如果您只需要表中的一个随机行,那么您可以使用函数RAND():的纯SQL来完成它

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

使用ORDER BY RAND()并将结果限制为1。这避免了您必须查询计数,然后最终遍历ResultSet,直到找到随机条目。

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

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

LIMIT子句可用于约束SELECT语句返回的行数。LIMIT接受一个或两个数字参数,这两个参数必须都是非负整数常量(使用准备语句时除外(。

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

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

最新更新