- Database Created… ✅
- Table Created… ✅
Alderaan System targeted… ✅
- List of Customers Saved to Table… ❌
As you can see our
death star, database, is not quite fully operational yet. Let’s keep working toward making this weapon system JDBC connection perform some useful work. Creating databases and tables is all good and well but our core functionality is actually turning our Java data into data that we can store in our tables and then retrieving it back out of the database at a later date.
This is done with the SQL
INSERT INTO statement. We
INSERT a set of values, in the same order as the columns of our table,
INTO our table. We will continue to use the
Statement interface to implement this SQL command, although we challenge you to browse the PreparedStatement Documentation to see how you can implement a more efficient solution on your own.
Let’s take a look at a sample insert statement in SQLite:
INSERT INTO CUSTOMERS VALUES (1010, "Jack", "Delangey", "[email protected]", "555-867-5309");
We don’t want to hardcode values into our SQL expression like the example above though, we want our
CustomerDaoService to contain the logic to substitute each of these values for the properties of our
Customer class. The whole command will be concatenated together into a String that we can execute on our database using our
.saveCustomers() method and inside the
try block, we’ve created a
for-each loop that iterates over each
customers. Inside the loop is our SQL String,
insertIntoCustomer with five locations, marked by “HERE” that need to be changed to the five instance properties of the current iteration of
customer. Change each “HERE” to its corresponding
for-each loop, call the
executeUpdate() on the
Statement instance, pass in the
insertIntoCustomer to the method.
Navigate to BusinessLogic.java, inside the
.main() method, add a call to the updated
.saveCustomers() method of the
CustomerDaoService class, pass in the
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-22.214.171.124.jar viewmodels.BusinessLogic.
- Just like that… victory to the Empire!