Java - Connecting to MySQL with the JDBC driver
In this chapter, you will study databases in java by creating a simple database with a single table, and study how to establish the connection using the java.Java uses an API named JDBC(Java Database Connectivity) to connect to the database of Data. JDBC allows you to connect to a large number of database managers such as Oracle, MySQL, PostGre, etc.
What is JDBC?
JDBC (Java Database Connectivity) is a connection interface between the java program and the SQL database owned by the Oracle company, created by the company Sun Microsystems and available since JDK version 1.1. This technology is a driver that defines how the client has access to the MySQL database. The JDBC driver provides methods for querying and updating the data in the database. JDBC is a tool for relational databases.JDBC classes are contained in the package java.sql and javax.sql. JDBC allows multiple implementations in the same application. The API is based on a mechanism that helps to dynamically load the corresponding packages and save them with the Driver Manager. The JDBC API is used to create JDBC.
The JDBC API is used to complete the following tasks:
- Establish a connection to the relational database such as MySQL, Oracle, etc.
- Send SQL queries to be executed on the database server.
- Process The results returned by running the SQL.
JDBC
- JDBC-ODBC Bridge (Type 1): This driver uses the ODBC driver to connect to the server database. You have to have the ODBC driver installed in the machine you want to connect to the database, that's why this driver is outdated and should be used only when you have no choice.
- The Native API (Type 2): This type converts JDBC orders to call the database via a native driver on the client. You must have the API of the customer database installed on the machine in order to establish the connection.
- A driver written in java using a Middleware (Type 3): This type uses a network protocol to send messages to the intermediary server, which can communicate with different types of databases. This driver can be easily used with an applet but you need to have the server. Intermediate installed to work with this driver. This driver is not widely used because of its poor performance.
- A java driver using the native protocol (Type 4): This is the preferred driver because it directly calls the database by converting JDBC messages to a network protocol that is compatible with the server. We must use specific drivers, such as OJDBC provided by Oracle and MySQL Connector/J for MySQL databases.
JDBC API classes
Classes are in the packages java.sql. The 4 important classes are: DriverManager, Connection, Statement, and PreparedStatement, and ResultSet.
- DriverManager: responsible for loading and configuring the database.
- Connection: Authenticate to the database.
- Statement: Send the SQL query to the database.
- ResultSet: browse the results retrieved from the database in the case of a data selection.
Configuration is the most important thing when using the JDBC API. The first thing to do is to choose which class of driver to use. For MySQL, the driver is com.mysql.jdbc.Driver and for Oracle it's oracle.jdbc.driver.OracleDriver. Both implement the interface java.sql.Driver. You can find these two classes in their jar.
The second important thing is the database connection url. Each driver has its own url configuration but they have the same one. host, port et schema in the connection URL. For MySQL login, the format is jdbc:mysql://< HOST>:< PORT>:< DIAGRAM> .
Another important detail is the username and password to connect to the database.
To establish the connection to the MySQL database, you need to instantiate the object of the Connection class by specifying the url to access it. The getConnection() method creates the connection with:
Database Configuration
We will read the detailed configuration of the database from the files, so we can easily switch from Oracle to MySQL and vice to that by changing the following details:#mysql DB properties
#DB_DRIVER_CLASS=com.mysql.jdbc.Driver
#DB_URL=jdbc:mysql://localhost:3306/UserDB
#DB_USERNAME=usermysql
#DB_PASSWORD=usermysqlpw
#Oracle DB Properties
DB_DRIVER_CLASS=oracle.jdbc.driver.OracleDriver
DB_URL=jdbc:oracle:thin:@localhost:1571:MyDBSID
DB_USERNAME=useroracle
DB_PASSWORD=useroraclepw
Configuration is the most important thing when using the JDBC API. The first thing to do is to choose which class of driver to use. For MySQL, the driver is com.mysql.jdbc.Driver and for Oracle it's oracle.jdbc.driver.OracleDriver. Both implement the interface java.sql.Driver. You can find these two classes in their jar.
The second important thing is the database connection url. Each driver has its own url configuration but they have the same one. host, port et schema in the connection URL. For MySQL login, the format is jdbc:mysql://< HOST>:< PORT>:< DIAGRAM> .
Another important detail is the username and password to connect to the database.
Connecting to MySQL database
This program reads the properties and creates the connection with MySQL.
import java.io.FileInputStream;First, we read the database configuration from the property file, then load the JDBC driver and use DriverManager to create the connection. Calling the Class.forName() method is important because it creates an instance of the class, not with the new operator, but just creates it and doesn't use it. The object will be created in memory and connected by itself to DriverManager.
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBConnection {
public static Connection getConnection() {
Properties props = new Properties();
FileInputStream fis = null;
Connection con = null;
try {
fis = new FileInputStream("db.properties");
props.load(fis);
// load the Driver Class
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
// create the connection now
con = DriverManager.getConnection(props.getProperty("DB_URL"),
props.getProperty("DB_USERNAME"),
props.getProperty("DB_PASSWORD"));
} catch (IOException | ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
To establish the connection to the MySQL database, you need to instantiate the object of the Connection class by specifying the url to access it. The getConnection() method creates the connection with:
- The name of the database by specifying the url
- The username
- The password