Connect java to database (JDBC in 6 steps)
JDBC stands for Java DataBase Connectivity, which is a fancy name for a simple process - connecting a java app to a database. For connecting a java app to a database, you need to perform these steps.
1] Load and register a driver (driver is like a translator between java language and database language)
2] Create a connection (connection object is like a road or a path going from java app to database and back)
3] Create a statement (statement object is like a vehicle going on the road from java app to database and back)
4] Execute a query
5] Parse the result set (a result set is an object that a database returns when it processes the query)
6] Close the connection.
Here is how it looks like in the simplest possible code. Connecting Java to Oracle database.
public class DBConnectionBasic { public static void main(String[] args) throws Exception { // in case database is running on a remote server, here it gets the path to specification file // System.setProperty("oracle.net.tns_admin", "C:\\Oracle\\x86\\product\\12.1.0\\client_1\\Network\\Admin"); // step 1] Class.forName("oracle.jdbc.driver.OracleDriver"); // ojdbc6.jar needs to be on the class path // step 2] Connection con = DriverManager.getConnection("jdbc:oracle:thin:@ETRMP", "SystemConsultant", "z49xt1e5"); // step 3] Statement st = con.createStatement(); // step 4] ResultSet rs = st.executeQuery("select * from xxx"); // step 5] while (rs.next()) { //... } // step 6] con.close(); } }
JDBC is a piece of technology that stands between a java app and a database to enable communication. It is a part of Java Standard Edition.
It can be seen as a set of specifications (guidelines) that is defined by Java vendor. These specifications are then implemented by a database vendor - these are the Drivers that you need to download and load (step 1).
While loading, what happens under the hood is that the driver registers itself with the java app. It happens automatically because in each driver software there is a Driver class and inside of this class there is a static block of code responsible for registering. From a user perspective, all we need to do is just load the driver, the registration takes care of itself.
For each database, there is a different driver software. The driver needs to be downloaded from the web as a .jar file and added to the classpath. In this way, a java application can talk to any database (Oracle, MySQL, Postgress, SQLite..).
Even though we have a different driver for each database, the beauty of JDBC is that it has a Standart API, independent of a particular database. That means that the steps described above will remain the same regardless if you are connecting to Oracle, MySQL, or SQLite. The only thing that changes is of course the name of the driver you are loading and the database credentials.
Most JDBC drivers are developed in Java and so they are not only database-independent but also platform-independent.