Search code examples
javamysqljdbcuser-inputresultset

How do I select specific MySQL row in Java using Scanner user_input Integer variable in ResultSet?


I have my tables already set up in MySQL and believe they are all connected correctly, and I am simply trying to display specific information. I am asking for user input and using that integer value as an object for result.absolute(). Whenever I run the timeresult input, I get the incorrect row for "actualtime". Is it the java code or some MySQL setting that results in the incorrect row to be displayed? All of the other info from println's is correct.

public static void main(String[] args) throws Exception {      

    Scanner user_input = new Scanner( System.in );

    String dayinput;
    System.out.print("Choose A Day (1-7): ");
    dayinput = user_input.next();

    //Accessing driver from the JAR file
    Class.forName("com.mysql.jdbc.Driver");

    //Creating a variable for the connection called "con"
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/axamschedule","root","password");
    //jdbc:mysql://localhost:3306/shows-----> This is the database
    //root is the database username
    //password is the database password

    System.out.println("Connected To Database");

    //Creating query for Sundays Table
    if (dayinput.equals("1")){
            PreparedStatement statement = con.prepareStatement("select * FROM suntimes, days, shows WHERE (days.idday = suntimes.idday and suntimes.idshow = shows.idshow)");

            //Creating a variable to execute query
            ResultSet result = statement.executeQuery();

            System.out.println("---------------------");

            Integer timeinput;
            System.out.print("Choose A Timeslot (1-24): ");
            timeinput = 0;
            timeinput = user_input.nextInt();


            if(result.absolute(timeinput)){

                    System.out.println("Time: " + result.getString("actualtime"));
                    System.out.println("Day: " + result.getString("day"));
                    System.out.println("Title: " + result.getString("title"));
                    System.out.println("Length: " + result.getString("length"));
                    System.out.println("Host: " + result.getString("author"));
            }                      
    }

     user_input.close();
   else{
         System.out.println("No Info");
   }

Solution

  • The resultset that you are getting is not sorted. The order that they are being returned is determined my mysql.

    try

    select * FROM suntimes, days, shows WHERE (days.idday = suntimes.idday and suntimes.idshow = shows.idshow) order by actualtime;