Search code examples
javaprepared-statementsetter

How do I call a method within a setString


I am trying to use a setString to call a method from another class, but I get an error message that says that cannot be resolved to a variable.

In my Tag class, I have:

import java.util.List;
import models.Book;


public class Tag {

    private String isbn_13;
    private String tag_name;
    
    public Tag(String isbn, String tagName) {
        this.isbn_13 = isbn;
        this.tag_name = tagName;
    }
    
    public Tag() {
        this.isbn_13 = null;
        this.tag_name = null;
    }
    
    public String getIsbn13() {
        return isbn_13;
    }

    public void setIsbn13(String isbn) {
        this.isbn_13 = isbn;
    }
    
    public String getTag() {
        return tag_name;
    }
    
    public void setTag(String tagName) {
        this.tag_name = tagName;
    }
    
    public void add(List<Tag> book_tags) {
        // TODO Auto-generated method stub
        
    }

}

Now, in my TagImpl class, the relevant method is

public boolean addTag(Tag tag) {
        try {
            connection = DAOUtilities.getConnection();
            String sql = "INSERT INTO Book_tags VALUES (?, ?)"; 
            stmt = connection.prepareStatement(sql);
            
            stmt.setString(1, tag.setIsbn13(isbn)); // Error here "isbn cannot be resolved to a variable"
            stmt.setString(2, tag.setTag(tagName)); // Error here "tagName cannot be resolved 
                                                    // to a variable"
            
            if (stmt.executeUpdate() != 0)
                return true;
            else
                return false;
            
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources();
        }
    }

I have looked at all the documentation I can think of, and the tutorials I can find, and all of them look like this is correct. The only difference is that some of them show empty parentheses, i.e. stmt.setString(1, tag.setIsbn13()); but that just gives a different error, "The method setIsbn13(String) in the type Tag is not applicable for the arguments ()" Also, it makes no difference if I change (isbn) to (isbn_13) or (tagName) to (tag_name) -- it still "cannot be resolved to a variable.


Solution

  • You have to get the isbn_13 and tag_name from tag and set into stmt.

    Replace

    stmt.setString(1, tag.setIsbn13(isbn)); 
    stmt.setString(2, tag.setTag(tagName));
    

    with

    stmt.setString(1, tag.getIsbn13()); 
    stmt.setString(2, tag.getTag());