使用PreparedStatement时com.mysql.jdbc.exceptions.MySQLSyntaxErrorException

时间:2015-10-16 20:54:02

标签: java mysql sql jdbc

我正在尝试执行一个查询,该查询返回名称和姓氏连接的学生等于搜索关键字参数。

为此,我在我的班级中执行此操作,该班级管理与Student班级的数据库相关的任何内容。

执行查询时,我收到以下错误:

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:

出了什么问题?我已经检查了正确的way to use concat

mysql数据库中

namelastNameVARCHAR

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;
}

1 个答案:

答案 0 :(得分:3)

您的问题是您使用

准备语句
preparedStatement = dbConnection.prepareStatement(selectSQL);

这是正确的,但是当您尝试执行PreparedStatement时,再次提供selectSQL字符串:

rs = preparedStatement.executeQuery(selectSQL);

这是不正确的。你已经准备好了这个陈述,所以当你要执行它时,你只需要做

rs = preparedStatement.executeQuery();
相关问题