gpt4 book ai didi

java - 在 DAO 中使用准备好的语句检索数据时出现问题

转载 作者:行者123 更新时间:2023-12-02 04:05:16 26 4
gpt4 key购买 nike

public class StudentDAO extends ConnectorDAO {

private List<StudentBean> studentList = new LinkedList<>();
private StudentBean studentBean;

public List<StudentBean> retrieveStudents() {

Connection connection;

try {
String myQuery = "SELECT ?, ?, ? FROM Students";
connection = getConnection() // getConnection() comes from superclass

PreparedStatement preparedstatement = connection.prepareStatement(myQuery);
preparedStatement.setString(1, "firstname");
preparedStatement.setString(2, "lastname");
preparedStatement.setString(3, "studentID");

ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
studentBean = new StudentBean();
studentBean.setFirstName(resultSet.getString("firstname"));
studentBean.setLastName(resultSet.getString("lastname"));
studentBean.setID(resultSet.getInt("studentID"));
studentList.add(studentBean);
}
} catch (Exception e) {
// Error handling stuff
} finally {
// close connection, resultset and preparedstatement
}

}
}

我的 Eclipse 中显示错误。在我设置 StudentBean 的 ID 的行上。我的数据库中studentID的数据类型是Int。我不确定如何检索它。谁能帮我?当我使用准备好的语句中使用的参数进行查询时,使用 Statement 对象时它会起作用。

最佳答案

您用于构建查询的代码不正确:

        String myQuery = "SELECT ?, ?, ? FROM Students";
connection = getConnection() // getConnection() comes from superclass

PreparedStatement preparedstatement = connection.prepareStatement(myQuery);
preparedStatement.setString(1, "firstname");
preparedStatement.setString(2, "lastname");
preparedStatement.setString(3, "studentID");

不可能:查询字符串的格式如下(示例):

String myQuery = "SELECT firstname, lastname, studentID FROM Students WHERE studentID=?";

这些参数只能用于变量,不能用于列名、表名等。

因此,一旦您有了这样的代码,您就可以在 studentID 上查询(不是您的目标,仅用于示例):

preparedStatement.setInt(1, someStudentID);

将与 preparedStatement 一起发送到 DBMS,然后 DBMS 替换 ?值为someStudentID .

关于java - 在 DAO 中使用准备好的语句检索数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com