0

I am trying to execute a query that returns a student whose name and last name concatenated equal the search key parameter.

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:

What's wrong? I have checked that's the correct way to use concat.

name and lastName are VARCHAR in the mysql database.

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; } 
4
  • What is the complete error message you're getting? Consider changing your catch blocks to something that will print all information available (not just print the stack trace) - for debugging rethrow it as throw new RuntimeException(e); to see if that yields a more specific error message. Commented Oct 16, 2015 at 21:37
  • Also, you can try deleting the trailing semicolon (not sure it will help but some JDBC drivers don't like them) Commented Oct 16, 2015 at 21:39
  • 1
    preparedStatement.executeUpdate(); ??? Commented Oct 16, 2015 at 23:42
  • I agree with @PetterFriberg; that .executeUpdate() ain't gonna work. But also, what is the StudentDB reference and what is the .setStudentAttributes method call actually doing? I think you will have to add more detail to get help with this - Commented Oct 16, 2015 at 23:52

1 Answer 1

3

Your problem is that you prepare the statement with

preparedStatement = dbConnection.prepareStatement(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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.