我收到错误消息(java.sql.SQLException) java.sql.SQLException: Before start of result set
当我试图从MySQL数据库获取记录时。这是我正在使用的代码:
public TimelineJDBC(String name, String startTime){
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost/TimeLineDB";
final String USER = "root";
final String PASS = "XXXX";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
String sql= "SELECT * FROM TIMELINE WHERE NAME= 'MyLife2' AND STARTTIME= '2008-02-01';";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
this.timeline.setId(rs.getInt("ID"));
this.timeline.setName(rs.getString("NAME"));
this.timeline.setDescriprion(rs.getString("DESCRIPTION"));
this.timeline.setStartTime(rs.getString("STARTTIME"));
this.timeline.setEndTime(rs.getString("ENDTIME"));
this.timeline.setPicture(rs.getString("PICTURE"));
TimeUnit enumVal = TimeUnit.valueOf(rs.getString("SCALE"));
this.timeline.setScale(enumVal);
}
catch(SQLException ex){
System.err.println("Error in retrieving a timeline record from database:"+ ex.getMessage());
}
catch (Exception e){
System.err.println(e.getMessage());
}
}
尝试阅读结果集this.timeline.setId(rs.getInt("ID"));
后
抛出此SQLException:(java.sql.SQLException) java.sql.SQLException: Before start of result set
我知道你必须转到下一个结果集(rs.next();
)的问题,但这似乎没有帮助,因为下一个结果集为null。
这是一个截图,显示初始结果集中返回的内容:
http://imgur.com/fjZoYF8
当尝试在同一个数据库上手动运行查询时,会形成一个正确的ResultSet,因此问题似乎不在于数据库。
答案 0 :(得分:4)
你应该使用
while (rs.next()) { // for multiple rows
// get from rs here
}
或
if (rs.next()) { // for single row
// get from rs here
}
答案 1 :(得分:1)
while(rs.next()) {
this.timeline.setId(rs.getInt("ID"));
this.timeline.setName(rs.getString("NAME"));
this.timeline.setDescriprion(rs.getString("DESCRIPTION"));
this.timeline.setStartTime(rs.getString("STARTTIME"));
this.timeline.setEndTime(rs.getString("ENDTIME"));
this.timeline.setPicture(rs.getString("PICTURE"));
TimeUnit enumVal = TimeUnit.valueOf(rs.getString("SCALE"));
this.timeline.setScale(enumVal);
}
如果你保留了它而不是它将起作用