我试图从作者表中返回所有ID...但不起作用...只是返回第一个ID...但是如果我删除返回并放入打印,那么就会给我所有ID..
String url = "jdbc:postgresql://localhost/testdb";
String user = "test";
String password = "test*";
try {
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT id FROM authors");
rs = pst.executeQuery();
while (rs.next()) {
return rs.getInt(1);
}
最佳答案
return
语句默认返回返回的常量/变量的值,停止方法执行并离开该方法。对此进行了解释:Returning a Value from a Method
要返回查询执行的所有结果,您必须将结果存储在 List
中,然后返回此列表:
List<Integer> idList = new ArrayList<Integer>();
//accessing to the database and executing the query...
rs = pst.executeQuery();
while (rs.next()) {
//store the ids in the list
idList.add(rs.getInt(1));
}
//close all the resources...
//at the bottom of your method
return idList;
关于java - 返回查询 SELECT 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753047/