我是一名初级写作程序,我为我的任务创建了一个搜索记录功能。JDBC - 无效光标状态
public void searchRecord(){
for(int ct = 0; ct< 1; ct++){
System.out.println("Please insert student ID");
System.out.print("Student ID: ");//prompt for student ID to search
String data = k.nextLine().trim();
String sql = "SELECT * FROM Students WHERE StudentID = '"+data+"'";
try{
rs = st.executeQuery(sql);
if(rs.next()){
displayRecord();
rs.next();
showMenu();
}
else{
System.out.print("No record found. ");
ct--;
}
}catch (Exception ex){
System.out.println("Problem searching.");
}
}
但是,我试图从结果中获取数据后,它显示Invalid Cursor State
。 如果我想要检索的数据,我将不得不执行Display next record
方法是:
try{
if(rs.next()){
displayRecord();
}
else{
rs.previous();
System.out.println("No more records!");
}
}catch (Exception ex){
System.out.println("There is problem showing next data.");
}
我尝试添加“rs.next”在“displayRecord后”的搜索记录的方法,但它不会解决问题。无论如何要解决这个问题吗?
顺便说我的显示记录方法:
public void displayRecord(){//get and display data from current row of record
try{
String ID = rs.getString(1);
String fname = rs.getString(2);
String lname = rs.getString(3);
String conNo = rs.getString(4);
String mail = rs.getString(5);
String plate = rs.getString(6);
Date date = rs.getDate(7);
System.out.print("Student ID: "+ID+"\nName: "+fname+" "+lname+"\nCar Number: "+plate+"\nContact Number: 0"+conNo+"\nE-Mail Address: "+mail+"\nDate Registered: "+date);
}catch (Exception ex){
System.out.println(ex);
}
}
任何帮助或建议表示赞赏。
尝试使用'while rs.next()'而不是'if' – user75ponic
阅读[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)并且永远不要再这样做:'String sql = “SELECT * FROM Student WHERE StudentID ='”+ data +“'”' – mustaccio
@mustaccio omg,我现在了解SQL注入。谢谢你的提示。 @Polppan,但该方法只返回1行的结果,因为** StudentID **是一个唯一的键,并不适合使用'而rs.next()' –