Search code examples
javamysqlresultset

java.sql.SQLException: Before start of result set


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

        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?

Thank you in advance.


Solution

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

    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.