java.sql.SQLException:在结果集开始之前

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25879523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:51:23  来源:igfitidea点击:

java.sql.SQLException: Before start of result set

javamysqlresultset

提问by GreatGatsby

I'm facing a problem getting data from my MySqldatabase. My code is the following:

我在从MySql数据库中获取数据时遇到问题。我的代码如下:

        try {
        Connection con = datasource.getConnection();
        Statement stmt = con.createStatement();

        ResultSet rs;
        rs = stmt.executeQuery("SELECT tittle,date,path " +
                "FROM announcement "+
                "ORDER BY date");
        String tittle=rs.getString("tittle");
        String date=rs.getString("date");
        String text=rs.getString("path");


     if (!rs.isBeforeFirst())
     {
        out.println("<p>No data !</p>");
    }
     else
     {            
        out.println("<table class=\"data\">");
        out.println("<tr ><td class=\"sectionheader\"> tittle?</td><td            class=\"sectionheader\">date</td><td class=\"sectionheader\">text</td></tr>");

        while (rs.next()) {
            String row="";
            row  += "<td><a href=\"\"> "+tittle+ "</td>";
            row  += "<td>" + date + "</td>";
            row +="<td>"+text+"</td>";

            row +="</tr>";
            out.println(row);

        }

The error I get is "java.sql.SQLException: Before start of result set"Any tip of what I am doing wrong?

我得到的错误是"java.sql.SQLException: Before start of result set"任何提示我做错了什么?

Thank you in advance.

先感谢您。

回答by RP-

You access the data in a ResultSet object through a cursor. Initially cursor points to before first row.

您可以通过游标访问 ResultSet 对象中的数据。最初光标指向第一行之前。

while(rs.next()) {
      String tittle=rs.getString("tittle");
      ....

}

More to it, your query might return more than one row, in that case, you may want to store the results in a collection, List<Map<String, String>>, where each entry in the list represents one row from your query resutls and the map hold the column name vs column value.

更重要的是,您的查询可能返回不止一行,在这种情况下,您可能希望将结果存储在一个集合中List<Map<String, String>>,其中列表中的每个条目代表查询结果中的一行,而地图保存列名 vs列值。