我有一个包含列 id
,teacher_id
和name
的课程表。在PreparedStatement中获取错误的输出
这是我用来通过id获取课程的方法。
public static Course getById(int id) throws SQLException {
String query = "SELECT * FROM courses WHERE id = ?" ;
Course course = new Course();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
connection = (Connection) DriverManager.getConnection(ConnectDb.CONN_STRING, ConnectDb.USERNAME, ConnectDb.PASSWORD);
statement = (PreparedStatement) connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, id);
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
course.setId(resultSet.getInt("id"));
course.setName(resultSet.getString("name"));
course.setTeacherId(resultSet.getInt("teacher_id"));
}
}catch (SQLException e) {
System.err.println(e);
}finally{
if (resultSet != null) resultSet.close();;
if (statement != null) statement.close();
if(connection != null) connection.close();
}
return course;
}// end of method
当我运行这个方法,我得到一个输出ID:0,teacher_id:0
服务器日志说,我有一个SQLException
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
你有没有调试过代码?如果根本没有结果,你会得到那个返回值......也许你应该在那个时候抛出一个异常呢? –
或者只是不匹配任何行;我会打赌你给美元甜甜圈,“新课程”给你一个这些领域的零课程。第1步是**总是**调试:[*如何调试小程序*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) –
您可能没有数据库中该“id”的数据。而且,您看到的结果是int类型的默认值。 – Sachin