我试图理解为什么我不能用Java搜索数据库中的多个记录。它是一个Java jsp应用程序,但我似乎很难找出问题所在。我是jsp的初学者,但我相信不会有任何区别
try{
String myDriver = "org.gjt.mm.mysql.Driver";//db driver
String myUrl = database;//connect to db
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, user, password);//authenticating on database
String query = "SELECT Cus_ID, Cus_name, Cus_surname, Cus_mail, Cus_Address, Cus_telephone FROM customerdb";//mysql select statement
PreparedStatement sta = conn.prepareStatement(query); //prepared statement
ResultSet rst = sta.executeQuery(query);
while (rst.next())
{
String cusid = rst.getString("Cus_ID"); //variable to retrieve the customer from the database
String cusn = rst.getString("Cus_name");
String cussn = rst.getString("Cus_surname");
String cusm = rst.getString("Cus_mail");
String cusaddr = rst.getString("Cus_Address");
String custel = rst.getString("Cus_telephone");
if(!(customer.equals(cusid))){
request.setAttribute("al", "user not found");
request.getRequestDispatcher("account.jsp").forward(request, response); //and user will stay on login page
}if(customer.equals(cusid)){
System.out.println("hello" + cusid);
request.setAttribute("ID", cusid);
request.setAttribute("name", cusn);
request.setAttribute("surname", cussn);
request.setAttribute("mail", cusm);
request.setAttribute("address", cusaddr);
request.setAttribute("telephone", custel);
request.getRequestDispatcher("account.jsp").forward(request, response);
}else{
}
}
}catch(ClassNotFoundException | SQLException | HeadlessException ex) {
Logger.getLogger(LogInController.class.getName()).log(Level.SEVERE, null, ex);
}
答案 0 :(得分:0)
PreparedStatement#executeQuery()
方法不接受任何参数。改变这个:
ResultSet rst = sta.executeQuery(query);
到此:
ResultSet rst = sta.executeQuery();
使用此API时,这是一个常见的错误。您的代码可能还有其他问题,但这应该会有明显的改进。