T
T
Timofey Lanevich2018-09-21 19:25:59
MySQL
Timofey Lanevich, 2018-09-21 19:25:59

Request by id does not produce a result?

Hello, I'm making a request to return a field by its id, but it does not return a result, but if I request to display all the fields, then everything is ok.

public Student getById(int id) {
        Student student = new Student();
        PreparedStatement preparedStatement = null;
        String sql = "SELECT * FROM stud WHERE id=?";

        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id);

            ResultSet resultSet = preparedStatement.executeQuery();

            student.setId(resultSet.getInt("id"));
            student.setFirstName(resultSet.getString("first_name"));
            student.setSecondName(resultSet.getString("second_name"));
            student.setCourse(resultSet.getInt("course"));

            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return student;
    }

java.sql.SQLException: Before start of result set
Student{id=0, firstName='null', secondName='null', course=0}
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861 )
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2473)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java: 2568)
at service.StudentDao.getById(StudentDao.java:67)
at Main.main(Main.java:31)
I would appreciate your help, thanks for your time.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2018-09-21
@Timak31

....
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.first();
....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question