Hello,
I am trying to search teachers from database using first name and last name in java,
I am trying to passed parameters (String firstname, String lastname) into setString method. I have to get the result using first and last name.
But, it does not seem to work,I have to pass the unit test, and when i run the unit test, The unit test tells me that "no value specified for parameter 2".
What is the other way of doing it? as i can not seem to find it.
I did the same thing when i was searching by id and it worked.
here is the method that i used when i was searching by id
public Teacher findTeacher(int id) throws SQLException
{
Teacher teacher = new Teacher(0, null, null);
String selectSQL = "SELECT * FROM database_activity.Teacher WHERE id = ?";
PreparedStatement statement = conn.prepareStatement(selectSQL);
statement.setString(1, String.valueOf(id));
ResultSet resultSet = statement.executeQuery();
try {
while(resultSet.next())
teacher = new Teacher(Integer.parseInt(resultSet.getString("id")), resultSet.getString("firstname"),
resultSet.getString("lastname"));
}
catch (SQLException e)
{
}
return teacher;
}
I have Teacher class with constructor and getters and setters.
public class Teacher {
private int id;
private String firstName;
private String lastName;
public Teacher(int id, String firstName, String lastName)
{
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getID() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString()
{
return "id: " + id +"Name: " + firstName + "Surname: " + lastName;
}
What I have tried:
public List<Teacher> findTeacher(String firstName, String lastName) throws SQLException {
List<Teacher> list = new ArrayList<>();
Teacher teacher = new Teacher(0, null, null);
String query = "SELECT * FROM database_activity.Teacher WHERE firstname like %?% and lastname like %?%";
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, String.valueOf(firstName));
statement.setString(1, String.valueOf(lastName));
ResultSet resultSet = statement.executeQuery();
try {
while(resultSet.next())
teacher = new Teacher(Integer.parseInt(resultSet.getString("id")),resultSet.getString("firstname") , resultSet.getString("lastname"));
list.add(teacher);
}
catch (SQLException e)
{}
return list;
}