简体   繁体   中英

java.sql.SQLException: Before start of result set already have rs.next

So I am connecting to the database and I want to take from table votes the cows number to show it On Bar Chart but I get error "java.sql.SQLException: Before start of result set" but I have and rs.next can some one help me please

conn = DbCon.ConnectDb();
String sql = "SELECT * FROM votes";
try
{
      pst = conn.prepareStatement(sql);
      rs = pst.executeQuery();
      String cows = rs.getString("cows");
      if (rs.next())
      {
          int cowss = Integer.parseInt(cows);
          DefaultCategoryDataset dataset=new DefaultCategoryDataset();
          dataset.setValue(cowss ,"Votes", "Cows");
          dataset.setValue(20 ,"Votes", "Pigs");
          dataset.setValue(20 ,"Votes", "Dogs");
          dataset.setValue(50 ,"Votes", "Donkeys");
          JFreeChart chart = ChartFactory.createBarChart("Results", "", "Votes", dataset, PlotOrientation.VERTICAL , false, true, true);
          ChartFrame frame = new ChartFrame("Results", chart);
          frame.setVisible(true);
          frame.setSize(450,350);
          frame.setLocationRelativeTo(null);
          frame.setResizable(false);
     }
 }
 catch(Exception e)
 {
     JOptionPane.showMessageDialog(null, e);
 }

You need to call ResultSet.next() before reading the column value so that the cursor points the first row in the result:

if (rs.next())
{
    String cows = rs.getString("cows");
    int cowss = Integer.parseInt(cows);
    ...

You also don't really need a PreparedStatement here -- no parameterized queries. You can simply use a normal Statement .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM