查询语句报错
userDAO类的方法
public static List<User> getAlluser() throws SQLException{ User user=new User(); List<User> users=new ArrayList<User>(); Connection connection=DriverManager.getConnection(); PreparedStatement pst=null; String sqlString="select id,name,sex,age from student "; pst=connection.prepareStatement(sqlString); ResultSet rs=pst.executeQuery(); while (rs!=null) { user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setSex(rs.getString("sex")); user.setAge(rs.getInt("age")); users.add(user); } return users; }
测试类:
import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cn.qy.com.DAO.userDAO; import cn.qy.com.common.User; public class dbTest { public static void main(String[] args) { userDAO userDao=new userDAO(); try { List<User> users = userDao.getAlluser(); System.out.println("-------所有的用户信息如下------------"); for (User u:users) { System.out.println("编号:"+u.getId()+" 姓名:"+u.getName()+ " 性别:"+u.getSex()+" 年龄:"+u.getAge()+"<br>"); } } catch (SQLException e) { e.printStackTrace(); } } }
出现的异常是:
java.sql.SQLException: Before start of result set at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920) at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:855) at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2710) at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2851) at cn.qy.com.DAO.userDAO.getAlluser(userDAO.java:74) at dbTest.main(dbTest.java:38)