Search code examples
javasqljakarta-eeservlet-3.0setstring

The method setString(int, String) in the type PreparedStatement is not applicable for the arguments (int, String[])


I know that setString permits to insert a value in specified position, now I want get checkbox values from the jsp page in order to pass it to the database.

I defined the variable of checkbox as a String array since it may handle one or more values.

This is how I defined it the variable in the class:

public String[] rep;

This is how my servlet shall retrieve this parameter in the doPost method:

String[] rep = request.getParameterValues("rep");

and this is a line from my DAO class from the preparedStatement query:

st.setString(3, exam.rep);

but that is shown this error: The method setString(int, String) in the type PreparedStatement is not applicable for the arguments (int, String[])

the whole query

public static void  add(Exam exam) throws ClassNotFoundException, SQLException {
    Connection cnx;
    cnx = Connect.getConnection();
    String req = "insert into examen values (?,?,?)";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, exam.titre);
    st.setString(2, exam.question);
    st.setString(3, exam.rep);
    st.executeUpdate();
}

Solution

  • It would help if you can show us your SQL query. Prepared statements take a single value, not an array. As you define the first param as the index of the ? in your query to replace with corresponding second param. Something like this might suit your needs;

    String stmt = "INSERT INTO abc (some_field) VALUES (?);";
    PreparedStatement ps = conn.prepareStatement(stmt);
    String formatted = String.join(",", items);
    ps.setString(3, formatted);
    

    If you want to store an array value using your prepared statement then you should format your string in some way that you can convert it back into an array when reading from your DB.