How to connect MySQL database in java
Published: 2021-10-29 18:58:00

In this post, we're going to see Java Database Connectivity (<b>JDBC</b>) with MySQL. Connecting to database to have CRUD operations like <b>INSERT</b>, <b>SELECT</b>, <b>UPDATE</b> and <b>DELETE</b> is the "center of gravity" of almost every backend technology.
To connect java application with the MySQL database, mysqlconnector.jar file is required to be loaded. You can download this file from <a href="https://dev.mysql.com/downloads/windows/installer/8.0.html" target="_blank">here</a> or <a href="https://dev.mysql.com/downloads/connector/j/">check here</a>. 

To load the jar file, you can do this by setting the classpath permanently. To do this,  go to environment variable then click on new tab. In variable name write <b>classpath</b> and in variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar as <b>C:\yourfolder\mysql-connector-java-8.0.25</b>;
Then create a new project in your java text editor say Eclipse, Netbeans.


Next, load mysqlconnector.jar file in your project by right clicking on it. I'm using <b>Eclipse</b> as my text editor, do the following to load the jar file in your project.
<b>1.</b>Right-click on your project.
<b>2.</b>Select Build Path.
<b>3.</b>Click on Configure Build Path.
<b>4.</b>Click on Libraries, select Add External JARs.
<b>5.</b>Select the jar file from the required folder.
<b>6.</b>Click and Apply and Ok.

For **Ubuntu users**, you might find <a href="https://help.ubuntu.com/community/JDBCAndMySQL">this</a> helpful.

<b>NOTE:</b> For whatever text editor you are using, You should be able to load that file.
Next after loading the jar file in your project, create a java class say <b>Users</b> to illustrate how to connect java to MySql database using com.mysql.jdbc.Driver driver class.

<b>Code Example</b>
```java
import java.sql.*;  
public class Users {

	public static void main(String[] args) {
		try{ 
			
Class.forName("com.mysql.cj.jdbc.Driver");
//Class.forName("com.mysql.jdbc.Driver"); // this has been deprecated
String connectionString = "jdbc:mysql://localhost:3306/db_name";
String db_username = "yourdatabase_username";
String db_password = "yourdatabase_password";
  
Connection con = DriverManager.getConnection(connectionString,
                                           db_username,
                                           db_password);  
	
			Statement stmt=con.createStatement();  
			ResultSet rs=stmt.executeQuery("select * from users");  
			while(rs.next()) {
				
			int id = rs.getInt("id");
	        String firstName = rs.getString("first_name");
	        String lastName = rs.getString("last_name");
	        
	        String name = rs.getString("name");
	        String username = rs.getString("username");
	        String telephone_no = rs.getString("tel_no");
	        String address = rs.getString("address");
	      
	        
	        Date dateCreated = rs.getDate("created_at");
	        boolean isActive = rs.getBoolean("isActive");
	        int user_role = rs.getInt("user_role");
	        
	        System.out.format("%s, %s, %s,
                             %s, %s, %s, %s, %s, %s\n", 
                             id,firstName, lastName, dateCreated,
                             isActive, user_role, name, username,
                             telephone_no, address);
		  }
con.close();  
	}
catch(Exception e){ 
     System.out.println(e);
   }  
}  
  }


```
<b>Code Explanation:</b>
1. <b>Class.forName()</b> is the method loads the driver class for the mysql database (com.mysql.jdbc.Driver).
2. Next, we establish a database connection using <b>getConnection()</b> method on DriverManager class which takes in the url for the database host, database username and password.
3. <b>con.createStatement()</b> is used to create a statement instance on the database connection object (con). Statement is used for accessing database. Statement interface cannot accept parameters and is useful when you are making static SQL statements at runtime like SELECT.
4. <b>executeQuery()</b> method on the statement object(stmt) returns result set by fetching data from database by selecting data from users table.
5. In the next line, we use <b>while loop</b> and <b>rs.next</b> to iterate through the rows of data from users table in database and then capture cell data using getString(), getInt(), getDate() and getBoolean() to capture string, integer, date and boolean column data from the schema which are later printed on the screen using System.out.println().

<b>UPDATE QUERY CODE SNIPPET</b>
```java
Class.forName("com.mysql.cj.jdbc.Driver");
String connectionString = "jdbc:mysql://localhost:3306/db_name";
String db_username = "yourdatabase_username";
String db_password = "yourdatabase_password";
  
Connection con = DriverManager.getConnection(connectionString,
                                           db_username,
                                           db_password);
 String query = "UPDATE users SET first_name= ?,
                 last_name=? where id = ?";
      PreparedStatement preparedStmt=con.prepareStatement(query);
      preparedStmt.setString(1, "Dallington");
      preparedStmt.setInt   (2, 1);
      preparedStmt.executeUpdate();
      con.close();

```
<b>NOTE:</b> We use PreparedStatement interface not Statement when executing dynamic sql updates in java. PreparedStatement is suitable when you want to use SQL statements many times and it accepts input parameters at runtime which is not the same case with Statement interface. Statement interface is useful when you are running static SQL statements at runtime.

**Benefits of PreparedStatement over Statement Interface**
1. PreparedStatement can execute parameterized queries whereas Statement can only run static queries.
2. The PreparedStatement performs faster as compared to Statement because the Statement needs to be compiled everytime we run the code whereas the PreparedStatement compiled once and then execute only on runtime.

<b>DELETE QUERY CODE SNIPPET</b>
```java
Class.forName("com.mysql.cj.jdbc.Driver");
String connectionString = "jdbc:mysql://localhost:3306/db_name";
String db_username = "yourdatabase_username";
String db_password = "yourdatabase_password";
  
Connection con = DriverManager.getConnection(connectionString,
                                           db_username,
                                           db_password);
      String query = "DELETE FROM users where id = ?";
      PreparedStatement preparedStmt = 
      con.prepareStatement(query);
      preparedStmt.setInt(1, 3);
      preparedStmt.execute();
      con.close();
```
Because we pass parameters (e.g id in our code example) during the delete query at runtime, that's why we use PreparedStatement interface.

<b>INSERT QUERY CODE SNIPPET</b>
```java
Class.forName("com.mysql.cj.jdbc.Driver");
String connectionString = "jdbc:mysql://localhost:3306/db_name";
String db_username = "yourdatabase_username";
String db_password = "yourdatabase_password";
  
Connection con = DriverManager.getConnection(connectionString,
                                           db_username,
                                           db_password);
      String query = " insert into users (first_name, last_name, 
         username, telephone_no, age, address, isActive)"
        + " values (?, ?, ?, ?, ?, ?, ?)";

      PreparedStatement preparedStmt=con.prepareStatement(query);
      preparedStmt.setString(1, "Dallington");
      preparedStmt.setString(2, "Asingwire");
      preparedStmt.setString(3, "Dalton");
      preparedStmt.setString(4, "25670000000");
      preparedStmt.setInt(5, 33);
      preparedStmt.setString(5, "Kampala");   
      preparedStmt.setBoolean(6, true);
      preparedStmt.execute();
      con.close();
```

<b>Conclusion:</b> That's how you can have CRUD operations in java using driver class; <b>com.mysql.jdbc.Driver</b>. Hope you can use this as the building block for more interesting projects in java. Thank you for taking time to read through this post, see you in the next one!