dpepper
dpepper

Reputation: 23

Iterating through SQL results in Java

I am currently working on a project that is based on a simple SQL Database. What I need to happen is have the end-user prompted to enter their warehouse then from their pull a list of trucks from the DataBase and present the trucks one at a time so they user can input current mileage. I have the warehouse input working fine and I am able to retrieve the truck list from the input as well. I just can't find a way to present it one at a time for current mileage input. Below is the code I have so far:

public class PreventativeMaintenance {

public static void main(String[] args) throws Exception 
{
    Scanner kb = new Scanner (System.in);
    System.out.print("Warehouse? ");

    Class.forName("com.mysql.jdbc.Driver");
    Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");

    String warehouse = kb.next();

    String query = "SELECT * FROM `new_schema`.`trucks` WHERE `warehouse` = '" + warehouse + "'";

    Statement st = con.createStatement();


    ResultSet rs = st.executeQuery(query);
  }
}

I have attempted to use an ArrayList of Objects called Truck and built the objects from the SQL Query. However, I ran into the same issue I am now where I cannot find a way to present the different truck numbers one at a time so the user may input their current mileage.

Upvotes: 2

Views: 107

Answers (1)

hitz
hitz

Reputation: 1110

You can try something like this:

    //once you get resultset rs after executing query
    while(rs.next()){  
        String truckName = rs.getString("<name of truck column>");
        setTruckMileage(truckName);
    }

    private void setTruckMileage(String truckName){  
        Scanner kb = new Scanner (System.in);
        System.out.print("Enter mileage for truck " + truckName +" : ");

        Integer mileage = kb.nextInt();

        //save mileage entered by user
    }

Upvotes: 1

Related Questions