我正在尝试执行一个查询,该查询返回一个学生的名字和姓氏连接起来等于搜索键参数。
为此,我在类(class)中执行此操作,为我的 Student
类(class)管理与数据库相关的所有内容。
执行查询时出现以下错误:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
怎么了?我已经检查过这是正确的 way to use 连接
。
name
和 lastName
是 mysql 数据库中的 VARCHAR
。
public static Student findStudent(String key) {
if (key == null) return null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
String selectSQL = "select * from project.students where concat(name, lastName) = ? ;";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, key);
Student student = null;
rs = preparedStatement.executeQuery(selectSQL);
if (rs.next()) {
StudentDB.setStudentAttributes(student, rs);
}
return student;
} catch(SQLException e) {
e.printStackTrace();
} finally {
close();
try {
if (preparedStatement != null) preparedStatement.close();
if (rs != null) rs.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
return null;
}
最佳答案
你的问题是你准备声明
preparedStatement = dbConnection.prepareStatement(selectSQL);
这是正确的,但是当您尝试执行 PreparedStatement 时,您会再次提供 selectSQL
字符串:
rs = preparedStatement.executeQuery(selectSQL);
这是不正确的。您已经准备好语句,所以当需要执行它时,您只需执行即可
rs = preparedStatement.executeQuery();
关于java - 使用 PreparedStatement 时出现 com.mysql.jdbc.exceptions.MySQLSyntaxErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33179378/