In this tutorial, you will learn how to connect to MySQL database in java. Here you will learn step by step guide to connect java application with a MySQL database. In order to connect MySQL database from Java, you need JDBC API. By JDBC, you will connect to any type of database like MySQL, Oracle etc.
Steps for java database connectivity:
- Import the package
- Load and Register the Driver
- Create the connection object
- Create the Statement object
- Execute the Query
- Close the connection object
you will need to import the package that includes all the JDBC classes and interface needed for database programming. Using import java.mysql.*;
To load and register the Driver you need to load a Driver class which is available in MySQL jar file. You need to download this jar file and import in your project.
Download Jar File: Download JDBC Driver
The forName() method is used to load and register the Driver.This forName() method is available in class Class.This method is a static method and dynamically load the Driver class.
Syntax of forName() method:
public static void forName(String className) throws classNotFoundException.
3. Create the Connection object:
The getConnection() method is responsible to connect java application to database.It is a static method of DriverManager class.This method contain 3 parameter “url”,”name” and “password”.
Syntax of getConnection() method:
public static Connection getConnection(String url,String name,String password)
throws SQLException
By using the Statement object we can send our SQL Query to database. The createStatement() method is used to create the statement. It is a method of connection interface.
Syntax of createStatement() method:
public Statement createStatement() throws SQLException
The executeQuery() method is used to execute queries to the database. It is a method of statement interface. Database Engine will execute a SQL Query and result in a place in a box. This box is called ResultSet.Resultset holds the result of the SQL Query. Java application can get all the result of SQL Query from ResultSet.
Syntax of executeQuery() method:
public ResultSet executeQuery(String url) throws SQLException.
The Final step is to close the connection by using the close() method. It is a method of connection interface. By closing the connection object ResultSet will be closed automatically.
Syntax of close() method:
public void close() throws SQLException
This is my database named employee and it contains a table called training. I want to connect to a MySQL database using java.
Java MySQL Database Connectivity with Example
Output: