方法 executeQuery() 不能在 PreparedStatement 或 CallableStatement 上获取参数。错误

2022-09-04 19:22:05

我在尝试连接并从数据库中检索数据时遇到此类错误。

方法 executeQuery() 不能在 PreparedStatement 或 CallableStatement 上获取参数。

我的代码是这样的。

String search = request.getParameter("searchstudent");
out.println(search);

String connectionURL = "jdbc:sqlserver://localhost:1433;databaseName=Chingdb;   integratedSecurity=true;";
 Connection connection = null;
 PreparedStatement pstatement = null;
 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
 ResultSet rs = null;
int updateQuery = 0;


if(request.getParameter("editstudent")!= null){ 
    try {           
     connection = DriverManager.getConnection(connectionURL, "root", "root");
     String queryString = "SELECT P_ID, lname, fname, mname FROM stu_info Where lname = ?";
     pstatement = connection.prepareStatement(queryString);
     pstatement.setString(1, search);
     rs = pstatement.executeQuery(queryString);
        updateQuery = pstatement.executeUpdate();
        %>
        <TABLE cellpadding="15" border="1" style="background-color: #ffffcc;">
        <%
        while (rs.next()) {
        %>
        <TR>
        <TD><%=rs.getInt(1)%></TD>
        <TD><%=rs.getString(2)%></TD>
        <TD><%=rs.getString(3)%></TD>
        <TD><%=rs.getString(4)%></TD>
        </TR></TABLE>
        <% 

        rs.close();
        pstatement.close();
        connection.close();

        }
        }

    catch(Exception e){
    out.println(e);
    }

   }

答案 1

你不需要第二次查询字符串,因为你“告诉”准备的陈述字符串::

pstatement = connection.prepareStatement(queryString);

这将是正确的方法:

 pstatement = connection.prepareStatement(queryString);
 pstatement.setString(1, search);
 rs = pstatement.executeQuery();

答案 2

尝试

 rs = pstatement.executeQuery();

在 中创建准备语句时已指定查询

 pstatement = connection.prepareStatement(queryString);

推荐