gpt4 book ai didi

java - 如何使用准备好的语句从数据库中选择实体

转载 作者:行者123 更新时间:2023-11-29 23:19:47 25 4
gpt4 key购买 nike

在尝试添加可能具有相同 key 的学生之前,我正在尝试检查数据库中是否存在某个 key 。我有一个名为 DataBaseHandler 的类,它具有操作数据库的函数,如果给定的 id 存在,则 StudentAlreadyExist 函数返回 true,如果不存在,则返回 false。当我尝试运行该应用程序时,它给了我这个错误

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
*******

这是我的代码片段,用于测试学生是否存在

//check if the student exist
public boolean studentAlreadyExists(String id) throws SQLException{
//first connect to the database;
connectToDataBase();

selectSQL = "select name from student where idNumber like ?";
prstmt = con.prepareStatement(selectSQL);
prstmt.setString(1, id);

ResultSet rs = prstmt.executeQuery(selectSQL);
String dbname = null;
while(rs.next()){

dbname = rs.getString("name");
}

return dbname != null;
}

最佳答案

你之前已经准备好了,你不必再次传递queryString作为参数。

API: https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeQuery()

应该看起来像:

public boolean studentAlreadyExists(String id) throws SQLException{
connectToDataBase();

selectSQL = "select name from student where idNumber like ?";
prstmt = con.prepareStatement();
prstmt.setString(1, id);

/* Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.*/
ResultSet rs = prstmt.executeQuery();
String dbname = null;
while(rs.next()){

dbname = rs.getString("name");
}

return dbname != null;
}

关于java - 如何使用准备好的语句从数据库中选择实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27423658/

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