Connect Java With MySQL Database

Connect Java With MySQL

In this comprehensive tutorial we will connect Java with MySQL Database. To connect Java with MYSQL Database we have to follow the following steps : 

Step 1 : Create Java Maven project 

You can create Maven Java Project using IntelliJ IDEA. Just give name of project DBConnect. Then choose build system Maven. And Click on Advanced Settings and write ground id org.codewitharjun or any name you want and ArtifactId DBConnect or any name. 
Create New Java Project
Create New Java Maven Project

Step 2 : Create MySQL Database and Table

Create a MySQL Database using XAMPP

  • Give name of the Database DBConnect.
  • Create a table student with columns age, name, address.
  • Insert data into table. 
Create MySQL database of name DBConnect.
Create MySQL database of name DBConnect.
Create table student
Create table student
Add age, name and address columns in student table
Add age, name and address columns in student table
Insert data into database
Insert data into database

Step 3 : Write Java Code to Connect with MySQL

Now create Java class inside src>main>java with name DBConnect.java. Then write code including the following steps:

  • Register the JDBC driver class.
  • Establish a connection to the MySQL database.
  • Create a statement for executing queries.
  • Execute SQL queries to retrieve data.
  • Close the connection.

DBConnect.java

Step 4 : Add MySQL dependency in pom.xml file.

pom.xml

After adding mysql dependency in pom.xml
After adding mysql dependency in pom.xml

Now just right click on the Java file and click on Run application. The output will be all the datas from the database. 

Output
Output

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top