Search in a table in Mysql with Java

Asked

Viewed 1,268 times

1

I’m having trouble trying to get something on the table, I’m new so I did it the way I know.

Button code:

livros.setPesquisarLivro(txtLivro.getText());
    try {
        modelo.setNumRows(0);

        for (ObjetoLivro c : livroDAO.pesquisarLivro(livros)) {
            modelo.addRow(new Object[]{
                c.getNomeLivro(),
                c.getAutor(),
                c.getGenero()});
                c.getAlunoLivro();
        }

    } catch (Exception e) {
    }

Research code:

public ArrayList<ObjetoLivro> pesquisarLivro(ObjetoLivro pesquisar) throws SQLException {
    ResultSet rs = ConnectionFactory.getStatement().executeQuery("SELECT IDLIVRO,NOMELIVRO,AUTOR,GENERO,NOMEALUNO FROM LIVRO WHERE NOMELIVRO LIKE  '%"+pesquisar+"%'");
    ArrayList<ObjetoLivro> livros = new ArrayList<ObjetoLivro>();
    while (rs.next()) {
        ObjetoLivro livros2 = new ObjetoLivro();
        livros2.setIdLivro(rs.getInt(1));
        livros2.setNomeLivro(rs.getString(2));
        livros2.setAutor(rs.getString(3));
        livros2.setGenero(rs.getString(4));
        livros2.setAlunoLivro(rs.getString(5));
        livros.add(livros2);
    }
    return livros;
}

Code of ConnectionFactory:

package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConnectionFactory {

private static Connection connection = null;
private static Statement statement;

static {
    try {
        Class.forName("com.mysql.jdbc.Driver");

        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/biblioteca",
                 "root", "");
        statement = connection.createStatement();

    } catch (Exception ex) {
        Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static Statement getStatement() {
    return statement;
}
}

Code of ObjetoLivro:

package Model;
public class ObjetoLivro {
private String nomeLivro,autor,genero,alunoLivro,pesquisarLivro;
private int idLivro;
public String getPesquisarLivro() {
    return pesquisarLivro;
}

public void setPesquisarLivro(String pesquisarLivro) {
    this.pesquisarLivro = pesquisarLivro;
}

public String getNomeLivro() {
    return nomeLivro;
}

public void setNomeLivro(String nomeLivro) {
    this.nomeLivro = nomeLivro;
}

public String getAutor() {
    return autor;
}

public void setAutor(String autor) {
    this.autor = autor;
}

public String getGenero() {
    return genero;
}

public void setGenero(String genero) {
    this.genero = genero;
}

public int getIdLivro() {
    return idLivro;
}

public void setIdLivro(int idLivro) {
    this.idLivro = idLivro;
}

public String getAlunoLivro() {
    return alunoLivro;
}

public void setAlunoLivro(String alunoLivro) {
    this.alunoLivro = alunoLivro;
} 
}

The return of the search code is:

[]

And my table shows nothing, after clicking the search button.

  • What is modelo.setNumRows(0);? Why do you call livroDAO.pesquisarLivro(livros); twice?

  • Are you searching directly at the bank ne? You need to enter all fields of the object in the query, because java has no way of knowing which fields this object has and which is related to the table columns.

  • 1

    Show the code of the classes ConnectionFactory and ObjetoLivro.

  • The.setNumRows(0) model, serves to start the table in column 0, because my table was manually configured.

  • The problem is just what I had commented, you are sending an objectolivro to the query, but java does not know what to search, you must inform which object field you want to search in the query.

  • Correct query: "SELECT IDLIVRO,NOMELIVRO,AUTOR,GENERO,NOMEALUNO FROM LIVRO WHERE NOMELIVRO LIKE '%"+ pesquisar.getNomeLivro() +"%'"

  • Read this: injection of SQL

  • Ah, it’s not just because you’ll put the results in a JTable that your doubt is about JTable or depends on knowledge intrinsic to JTable. In fact, your question is about the JDBC and you have no problem with your JTable in the scope of that question. So I took (again) the [jtable] tag and added the [jdbc tag].

Show 3 more comments

2 answers

1

The problem is that, in the section below, you are concatenating the class instance itself ObjetoLivro instead of the book name:

WHERE NOMELIVRO LIKE '%"+pesquisar+"%'");
//Deveria ser
WHERE NOMELIVRO LIKE '%"+pesquisar.getNomeLivro()+"%'");

Also, the ideal would be for you to use a PreparedStatement instead of a Statement, since the first has advantages over the second as you can see here.

With a PreparedStatement your code would look like this:

Connectionfactory:

public class ConnectionFactory {
    //O resto do código

    public static PreparedStatement createPreparedStatement(String sql) throws SQLException {
        connection.prepareStatement(sql);
    }
}

Research code:

public ArrayList<ObjetoLivro> pesquisarLivro(ObjetoLivro pesquisar) throws SQLException {
    PreparedStatement ps = ConnectionFactory.createPreparedStatement("SELECT IDLIVRO,NOMELIVRO,AUTOR,GENERO,NOMEALUNO FROM LIVRO WHERE NOMELIVRO LIKE ?");
    ps.setString(1, "%" + pesquisar.getNomeLivro() + "%");

    ResultSet rs = ps.executeQuery();

    ArrayList<ObjetoLivro> livros = new ArrayList<ObjetoLivro>();
    while (rs.next()) {
        ObjetoLivro livro = new ObjetoLivro();
        livro.setIdLivro(rs.getInt(1));
        livro.setNomeLivro(rs.getString(2));
        livro.setAutor(rs.getString(3));
        livro.setGenero(rs.getString(4));
        livro.setAlunoLivro(rs.getString(5));
        livros.add(livro);
    }
    return livros;
}
  • Your method did not work fully, because even if I click on search it is without anything search, but stopped appearing the [] return.

  • @Marcoskropp The query is case-sensitive. The string you use in the query is in the same case as the string in the database?

  • Yes I am testing everything in lower case, I believe that the research is not appearing in function of the search method.

0

The first problem with your code, as others have pointed out, is this:

'%"+pesquisar+"%'"

What you wanted was this:

'%"+pesquisar.getNomeLivro()+"%'"

Another possibility is to exchange this:

public ArrayList<ObjetoLivro> pesquisarLivro(ObjetoLivro pesquisar) throws SQLException {

That’s why:

public List<ObjetoLivro> pesquisarLivro(String pesquisar) throws SQLException {

That’s because I believe you want a method that:

"from a title or part of a book title to be researched, return all books that have that title".

That’s a little different than a method that:

"from a book that has some title, return all books that contain the title of the book provided within its own titles".

However your code still has other problems:

To solve these problems, here’s how your ConnectionFactory and its research method:

package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {

    public static Connection connect() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/biblioteca", "root", "");
    }
}
public List<ObjetoLivro> pesquisarLivro(String nomeLivro) throws SQLException {
    List<ObjetoLivro> livros = new ArrayList<>();
    String sql = "SELECT IDLIVRO, NOMELIVRO, AUTOR, GENERO, NOMEALUNO FROM LIVRO WHERE NOMELIVRO LIKE ?";
    try (
        Connection conn = ConnectionFactory.connect();
        PreparedStatement ps = conn.prepareStatement(sql);
    ) {
        ps.setString(1, "%" + nomeLivro + "%");
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                ObjetoLivro livros2 = new ObjetoLivro();
                livros2.setIdLivro(rs.getInt(1));
                livros2.setNomeLivro(rs.getString(2));
                livros2.setAutor(rs.getString(3));
                livros2.setGenero(rs.getString(4));
                livros2.setAlunoLivro(rs.getString(5));
                livros.add(livros2);
            }
        }
    }
    return livros;
}
  • Victor Stafusa your method also did not work, because there is an error in setParameter where I do not know how to fix.

  • @Marcoskropp I edited the answer and corrected. It was a mess I made with the name of the method.

  • Again did not work, because with this Connectionfactory ocoore several errors.

  • @Marcoskropp What errors? Are compilation errors or SQLExceptions? Could post the entire error message(s) (s)?

  • The software tells me to add import libraries, but when I pull it does not let me compile without error.

  • @Marcoskropp This suggests that your problem then is something else that is not related to this question. In this case, I suggest asking a new question and ask her about these library import errors.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.