java sql random row print

时间:2017-07-21 05:57:25

标签: java database wamp

我尝试打印随机行,但我不能,我怎么能打印随机行?

- 数据库名称测试  -table name user_data

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class sqlconnect {
public static void main(String args[]) {
try {

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root",""); 
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from user_data ORDER BY RANDOM() OFFSET 0 ROWS FETCH NEXT 1 ROW ONLY");

while(rs.next())

System.out.println(rs.getString(1)); 
con.close();
} 
catch (Exception e){ System.out.println(e);} 
}
}

我尝试此代码这是错误消息

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OFFSET 0 ROWS FETCH NEXT 1 ROW ONLY' at line 1

1 个答案:

答案 0 :(得分:3)

如果您只想打印一个随机行,请使用LIMIT 1告诉MySQL将结果集限制为一条记录:

SELECT * FROM user_data ORDER BY RAND() LIMIT 1

<强>代码:

ResultSet rs = stmt.executeQuery("SELECT * FROM user_data ORDER BY RAND() LIMIT 1");

您对FETCH NEXT的使用似乎是SQL Server语法(q.v. here)。