2015-10-16 28 views
0

我想执行一个查询,返回一个学生的名字和姓氏连接起来等于搜索关键字参数。com.mysql.jdbc.exceptions.MySQLSyntaxErrorException当使用CONCAT

为此,我在我的班级为我的Student类管理与数据库相关的任何事情。

当执行查询我得到下面的错误:

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:

有什么不对?我检查了这是正确的way to useconcat

namelastNameVARCHAR在mysql数据库中。

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

什么是你得到的完整的错误信息?考虑将catch块更改为可打印所有可用信息的东西(不仅仅是打印堆栈跟踪) - 对于调试,将其重新抛出为抛出新的RuntimeException(e);以查看是否会产生更具体的错误消息。 –

+0

此外,您可以尝试删除尾随分号(不确定它会有帮助,但一些JDBC驱动程序不喜欢它们) –

+1

preparedStatement.executeUpdate(); ??? –

回答

2

你的问题是,你有

preparedStatement = dbConnection.prepareStatement(selectSQL); 

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

rs = preparedStatement.executeQuery(selectSQL); 

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

rs = preparedStatement.executeQuery();