使用PreparedStatement时com.mysql.jdbc.exceptions.MySQLSyntaxErrorException [英] com.mysql.jdbc.exceptions.MySQLSyntaxErrorException when using PreparedStatement
问题描述
我正在尝试执行一个查询,该查询返回一个名和姓串联在一起的学生,该名与搜索键参数相等.
I am trying to execute a query that returns a student whose name and last name concatenated equal the search key parameter.
为此,我在我的类中执行此操作,该类为我的Student
类管理与数据库相关的任何事情.
For that I am doing this in my class that manages anything related to the database for my Student
class.
执行查询时,出现以下错误:
When the query is executed I am getting the error that follows:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
怎么了?我已经检查过这是正确的使用方式 concat
.
What's wrong? I have checked that's the correct way to use concat
.
name
和lastName
是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;
}
推荐答案
您的问题是您准备的语句是
Your problem is that you prepare the statement with
preparedStatement = dbConnection.prepareStatement(selectSQL);
这是正确的,但是当您尝试执行PreparedStatement时,再次提供了selectSQL
字符串:
which is correct, but then when you try to execute the PreparedStatement you supply the selectSQL
string again:
rs = preparedStatement.executeQuery(selectSQL);
那是不正确的.您已经准备好了该语句,因此当需要执行该语句时,您只需
That is incorrect. You've already prepared the statement, so when the time comes to execute it you just do
rs = preparedStatement.executeQuery();
这篇关于使用PreparedStatement时com.mysql.jdbc.exceptions.MySQLSyntaxErrorException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!