Working with databases can be done from the terminal, and really, is accessible via checking documentation. Now, we will look at working with JDBC API, which will then allow us to work with a database from a Java application. JDBC is simply a middleman application that sits between the database level and the Java application. To use a particular data source from an application, we will need JDBC driver for that data source: something that is provided by all main database applications → will need to download the driver.
It allows us to execute SQL queries through the Java application
We’ll look at SQLite, but these can be then applied to any database.
SQLite Commands
⇒ Order by and Joins
What if we want to select something that is part of multiple tables? We will use the join clause:
This query should return the song tracks, titles and album names where, from their respective tables, we have the condition songs.album = albums._id to be true. There are multiple types of joins, and really, the join above that was demonstrated is a use of INNER JOIN. So, the above is the same thing as:
Here are the other ones:
Left Join: The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.
Right join: The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is 0 records from the left side, if there is no match.
Full join: The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right (table2) table records.
Now, lets look at JDBC. We will need to first install the database driver, and add it to the application. The setup looks like this:
We create an initial connection, and a statement object, in which we can then make changes to the DB. For insertion, updating, and deleting, we just simply execute() the SQL query. For selecting, we can get those results from the database into the Java program through:
Now, for actual projects, it will make sense to define global constants (for things such as table names, column names, etc.). In addition, it will make sense, and be more practical, to perform these initializations inside of a class, like so: