MySQL javafx搜索类

MySQL javafx搜索类,mysql,javafx,sql-like,Mysql,Javafx,Sql Like,我都快疯了。也许我错过了一些非常简单的事情。但我似乎无法让它工作。我收到了其他用户的帮助并编辑了我的代码。但真的无法让它发挥作用 这是我数据库中的表 +----------------+-----------------------+---------------------+ | colID | colTitle | colKeywords | +----------------+-----------------------+---

我都快疯了。也许我错过了一些非常简单的事情。但我似乎无法让它工作。我收到了其他用户的帮助并编辑了我的代码。但真的无法让它发挥作用

这是我数据库中的表

+----------------+-----------------------+---------------------+
|  colID         | colTitle              | colKeywords         |
+----------------+-----------------------+---------------------+
| 1              |  Jumanji              | comedy adventure    |
| 2              |  Moana                | adventure animation |
| 3              |  Shawshank Redemption | drama tearjerker    |
| 4              |  Avengers             | action              |
+----------------+-----------------------+---------------------+

        +-----------------------------+    +---------+    
Search: | adventure and action movies |    |button GO|
        +-----------------------------+    +---------+
我想做的是,如果我在文本字段中键入“冒险和动作电影”,在按下go按钮后,tableview中的结果应该是:

Jumanji
Moana
Avengers
我的更新代码:

public class UserMainPageController implements Initializable {



    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    @FXML
    private TableView table_title;

    @FXML
    private TableColumn titleCol;

    @FXML
    private TextField txt_search;




    @Override
    public void initialize(URL url, ResourceBundle rb) {




    }    



    @FXML
    private void logOut(ActionEvent event) throws IOException{

        Main.showUserLogin();

    }




    @FXML
    private void goSearch(ActionEvent event) throws IOException, SQLException{


       try{

        conn = SqlConnection.ConnectDB();
        String criteria = txt_search.getText();
        if (criteria.trim().length() == 0) { return; }
        String[] arryCriterion = criteria.split(" ");
        List<String> results = new ArrayList<>();

        for (int i = 0; i < arryCriterion.length; i++) {

            List<String> text = populateField(arryCriterion[i], conn);

            results.addAll(text);

        }

        ObservableList<String> observableList = FXCollections.observableList(results);

        table_title.setItems(observableList);


    }finally{
        conn.close();
    }
}   

    private List<String> populateField(String s, Connection conn) throws SQLException{

    List<String> myList = new ArrayList<>();

    String sql = "SELECT * FROM table_entry WHERE colTitle LIKE ? ";


    pst=conn.prepareStatement(sql);

    pst.setString(1, "%" + s + "%");
    rs = pst.executeQuery();
    while (rs.next()) {
        myList.add(rs.getString("colTitle"));
    }
    return myList;

    }


}
公共类UserMainPageController实现可初始化{
连接conn=null;
PreparedStatement pst=null;
结果集rs=null;
@FXML
私有表视图表标题;
@FXML
私有表列标题醇;
@FXML
私有文本字段txt_搜索;
@凌驾
公共void初始化(URL、ResourceBundle rb){
}    
@FXML
私有作废注销(ActionEvent事件)引发IOException{
Main.showUserLogin();
}
@FXML
私有void goSearch(ActionEvent事件)抛出IOException、SQLException{
试一试{
conn=SqlConnection.ConnectDB();
String criteria=txt_search.getText();
如果(criteria.trim().length()==0){return;}
字符串[]arryCriterion=criteria.split(“”);
列表结果=新建ArrayList();
对于(int i=0;i

如果我按下搜索按钮,tableview中似乎没有显示任何内容基本上,我的方法与@James_D的建议类似。首先从
数据库中获取所有数据。然后使用
Java
过滤数据

在我的
数据库中,我在每个关键字之间使用Unicode字符
信息分隔符三(U+001D)
。示例:
喜剧↔冒险
。我这样做是为了使用
String.split()
获取每个关键字

在应用程序中,我使用
FilteredList
来过滤
TableView
。如果DB(数据库)条目至少包含一个关键字,则将显示该条目<代码>!Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()),searkingFor)处理这个问题

此外,我还创建了一个
标记
类。这有助于我跟上形势。这些
标签看起来很糟糕,但是你可以用来自的想法来美化它们

代码:

主要内容:


如果您只需放置一个断点并单步执行这些代码,这将更容易进行故障排除。您是得到SQL结果还是问题在于将这些结果放入TableView?我创建了一个采用不同方法的示例应用程序。如果你明天还没有弄明白,如果我没有忘记,我会发布它。为什么不直接用Java过滤表,而不是每次都发送一个新的数据库请求呢?你看,比如说,嗨,塞德里克还没弄明白。。您的方法是否涉及每个关键字都有单独Id的方法?多对多方法?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    private final TableView<Movie> table = new TableView<>();


    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setWidth(450);
        stage.setHeight(550); 

        TableColumn colID = new TableColumn("ID");
        colID.setMinWidth(100);
        colID.setCellValueFactory(new PropertyValueFactory<>("colID"));

        TableColumn colTitle = new TableColumn("Title");
        colTitle.setMinWidth(100);
        colTitle.setCellValueFactory(new PropertyValueFactory<>("colTitle"));

        TableColumn colKeywords = new TableColumn("Keywords");
        colKeywords.setMinWidth(200);
        colKeywords.setCellValueFactory(new PropertyValueFactory<>("colKeywords"));

        DBHandler dbhandler = new DBHandler();
        FilteredList<Movie> filteredList = new FilteredList(dbhandler.getDBMovies());
        table.setItems(filteredList);
        table.getColumns().addAll(colID, colTitle, colKeywords);

        FlowPane flowPane = new FlowPane();
        TextField searchField = new TextField();
        searchField.setOnAction(event -> {
            List<String> searchingFor = new ArrayList();

            Tag tempTag = new Tag(searchField.getText());
            tempTag.getCloseButton().setOnAction((actionEvent) -> {
                flowPane.getChildren().remove(tempTag);
                if(flowPane.getChildren().isEmpty())
                {
                    filteredList.setPredicate(null);
                }
                else{
                    filteredList.setPredicate((t) -> {
                        return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
                    });
                }
            });
            flowPane.getChildren().add(tempTag);

            for(Node node : flowPane.getChildren())
            {
                searchingFor.add(((Tag)node).getText());
            }
            filteredList.setPredicate((t) -> {
                return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
            });

            searchField.clear();
        });

        HBox hbox = new HBox(searchField, flowPane);
        final VBox vbox = new VBox(table, hbox);
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }
}
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

/**
 *
 * @author Sedrick
 */
public class Movie {
    private static final String INFORMATION_SEPARATOR_THREE = "\u001D";

    private final IntegerProperty colID = new SimpleIntegerProperty();
    private final StringProperty colTitle = new SimpleStringProperty();
    private final StringProperty colKeywords = new SimpleStringProperty();

    public Movie(int colID, String colTitle, String colKeywords)
    {
        this.colID.set(colID);
        this.colTitle.set(colTitle);
        this.colKeywords.set(colKeywords);
    }


    public void setColID(int colID)
    {
        this.colID.set(colID);
    }

    public int getColID()
    {
        return this.colID.get();
    }

    public void setColTitle(String colTitle)
    {
        this.colTitle.set(colTitle);
    }

    public String getColTitle()
    {
        return this.colTitle.get();
    }

    public void setColID(String colKeywords)
    {
        this.colKeywords.set(colKeywords);
    }

    public String getColKeywords()
    {
        return this.colKeywords.get();
    }

    //Utility Methods
    //Converts a String of keywords to a list<String> of keywords
    public static List<String> KeywordsStringToList(String keywords)
    {
        String[] keywordsArray = keywords.split(INFORMATION_SEPARATOR_THREE);

        List<String> keywordsList = new ArrayList();
        for(String entry : keywordsArray)
        {
            keywordsList.add(entry);
        }

        return keywordsList;
    }

    //Convert a List<String> of keywords to a String of keywords
    public static String keywordsListToString(List<String> keywords)
    {
        return String.join(INFORMATION_SEPARATOR_THREE, keywords);
    }
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 *
 * @author Sedrick
 */
public class DBHandler {
    Connection connection;

    public DBHandler()
    {
        try 
        {
            connection = DriverManager.getConnection("jdbc:sqlite:movie.db");
            System.out.println("connected to db!");
        } catch (SQLException ex) 
        {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public ObservableList<Movie> getDBMovies()
    {
        String query = "SELECT * FROM MovieInfo";
        ObservableList<Movie> movies = FXCollections.observableArrayList();

        try(Statement statement = connection.createStatement();
                ResultSet result = statement.executeQuery(query))
        {
            while(result.next())
            {
                Movie movie = new Movie(result.getInt("id"), result.getString("title"), result.getString("keywords"));
                movies.add(movie);
            }
        } 
        catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        return movies;
    }

}
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;

/**
 *
 * @author Sedrick
 */
final public class Tag extends HBox{
    final private Label keyword;
    final private Button closeButton;

    public Tag(String keyword) {
        this.keyword = new Label(keyword);
        closeButton = new Button("x");
        this.getChildren().addAll(this.keyword, closeButton);
    }

    public String getText()
    {
        return keyword.getText();
    }

    Button getCloseButton()
    {
        return closeButton;
    }    
}