使用PreparedStatement时com.mysql.jdbc.exceptions.MySQLSyntaxErrorException
我正在尝试执行一个查询,该查询返回名称和姓氏连接的学生等于搜索关键字参数。
为此,我在我的class级中执行此操作,该class级管理与Student
类的数据库相关的任何内容。
执行查询时,我收到以下错误:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
怎么了? 我已经检查过这是使用 concat
的正确方法 。
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();