mercredi 27 avril 2016

Select one random data that have a common characteristic from a sqlite database

I have a database in sqlite that it has questions on it. Each question has a subject, question, answer, and level column. At the moment, I can ask for a subject and it will print me in a textField the question; however, It always selects the same question. How can I choose a random question that belongs to the subject Math? My code looks like this at the moment:

    question = new TextField();
    question.setPrefWidth(400.0);
    question.setPrefHeight(70.0);
    question.setStyle("-fx-font: 30 timesnewroman; -fx-base: #190707;-fx-text-fill: black;");




    startTestButton = new Button("START");
    startTestButton.addEventHandler(ActionEvent.ACTION, (e)-> {

        counterQuestions  = nQTextField.getText();
        System.out.println("Number of questions: " +  counterQuestions);

        try
        {
            String sql = "select * from Questions where Subject = ?";
            PreparedStatement pst = connectionQuestions.prepareStatement(sql);
            pst.setString(1,SsubjectTestField.getText());
            ResultSet rs = pst.executeQuery();
            if(rs.next())
            {
                question.setText(rs.getString("Question"));
            }
            else
            {
                System.out.println("No data for this subject");
            }
        }
        catch(Exception a)
        {
            System.out.println(a);
        }


        primaryStage.setScene(sceneMathTest);


    });
    startTestButton.setPrefWidth(200.0);
    startTestButton.setPrefHeight(50.0);
    startTestButton.setStyle("-fx-font: 30 timesnewroman; -fx-base: #2EFE64; -fx-text-fill: black;");

    createTestButtonPane.add(startTestButton,5,6);

THe frase that I use is : "select * from Questions where Subject = ?", however the * means all of them but it is choosing always the same one.

Thank you so much in advance.

Aucun commentaire:

Enregistrer un commentaire