ResultSet is all good and dandy, but what we really need back into our program is
Customer objects! In the previous exercise, we used the
.getString() method to pull data from a column and convert it to a string for use in printing. The
ResultSet class has a wide range of other
get methods that will return nearly any data from a column if of course that data type can be converted to the requested type.
Customer class stores its
ID as an integer and the rest of the properties are strings, making our implementation fairly easy so, we’ll stick to just two methods:
.getString(). Here are some of the other options available:
There is a generic
.getObject()method as well that returns the default Java object type corresponding to the column’s SQL type, following the mapping for built-in types specified in the JDBC specification.
Let’s get to creating our
Customer objects from information stored inside a SQL database!
We’ve cleared out the
while loop from our previous implementation, but we’ll keep the shell so we can still iterate over each row. Declare five variables, have their names match the instance variables found in the
Customer class, and don’t initialize them to anything yet.
Initialize each of the five variables to its applicable column using the appropriate method from the
ResultSet class. Initialize the variables on the same line as their declaration.
Still inside the
while loop, add a new
Customer to the local variable,
allCustomers, do this all in one line.
Head to BusinessLogic.java, you’ll notice we have taken care of adding the code to the file this time. We’ve also added some logic to completely clear out our class variable that holds our customers so that when we load customers back into the list we know they truly came from the database. We’ve also added a
.toString() method to our
Customer class and added some delays in the overall code to slow the console down a bit.
Run to continue.
Compile and run your program:
- Navigate to the
projectsfolder in the terminal (use ‘cd’ to change directories).
- Use the command
javac $(find . -name '*.java')to compile all
.javafiles in all subdirectories of the
- Run your program with the classpath variables like before:
java -classpath .:../sqlite-jdbc-184.108.40.206.jar viewmodels.BusinessLogic.